#web-development

2 messages · Page 189 of 1

inland oak
#

in CASCADE case, if parent element is deleted, then all its connected childs deleted too

#

PROTECT sounds like, parent element will not be able being deleted, until it is out of childs

desert estuary
#

anyone ?!

#

...

native tide
#

try placing the class definitions at the top?

jovial cloud
#

You need to import both Students and Admin as well as create the tables for those model classes

desert estuary
#
>>> Students.query.all()
[Student:Students.id Students.fullname Students.dialling_num Students.branch]
``` i dont get the content inside those
jovial cloud
jovial cloud
desert estuary
#

actually it is in the database

#

and here's the app

#

see the same info

jovial cloud
desert estuary
#

well i ahd this but it's kinda minor still bothers me when i first created the app i had been accessing all the modules or the files idk what to name them but i could access them easily with just for instance
i was typing

from models import student ... 

now i always have to include

from Flaskiproject.models import students,admin ... 

idk what changed
2) i still have the same problem of not accessing data from the db shell

jovial cloud
#

Regarding

  1. Check if the folder path you're running the commands from in your terminal has the same root as the 'models' module
  2. I just saw your previous code again, and noticed that you're calling the class attributes instead of the instance attributes
Admin.id should be changed to self.id and so on,
Same goes for Student.id and others```
desert estuary
#

also another thing i had the issue with is i couldn't render the whole table of the database

#
return render_template("Admin/profiles.html",Students = Students.query.get(1),date=eleganter_date)
```  i do understand about the get()
but that's the only way it rendered data from the database
#

i couldn't render all the data in the database while doing Students.query.all()

jovial cloud
desert estuary
jovial cloud
shrewd sand
#

I am trying to figure out why this purple space is there, and how to get rid of it>

#

The website only works on mobile right now, let me know if you know how to sort this

manic crane
#

when i do this does it delete the super user ?

dry obsidian
#

So I have a question, let's say I have a REST api backend. If the frontend and backend are hosted in the same host will there be a delay when I call the backend from the frontend?

#

Or does it depend on the internet connection

manic frost
dry obsidian
#

Wait so what will be faster?
1- Make a REST backend that will call an external Api and sort the data then return it

  • Call the external Api directly fromt the frontend then sort it
opaque rivet
#

@dry obsidian second option, but you might want the first option if you want to cache external API data and distribute it between users (resulting in less external API calls - which saves cost if its paid).

dry obsidian
#

But is there a big speed difference between the 2 options?

opaque rivet
#

The first option you're sending a request to your backend (and also to the external API), so it'll be slower by the amount of time to request your backend.

Not much, I'd say 200 ms more.

dry obsidian
#

Ok good to know thanks!

opaque rivet
#

I prefer to handle all API work on the backend, because it's easier to work with data using python than JS (opinionated) and it gives you the option to cache. Also if you request from the frontend, users can see the endpoint and abuse it. Routing it through your backend means you can rate limit each user.

dry obsidian
#

Ok I'll go with this option, it fits my project the best 👍

manic frost
#

@dry obsidian If the external API requires an API key, you can't go with the second option

dry obsidian
#

Oh true, didn't think about that cause I plan on using the YouTube API

wispy niche
#

Hello, Ive got some questions about Django apps within the framework that im hoping someone could better explain. I get the reason why you should create apps for user profiles and etc. but i am struggling to know when to create an app for something for a website.

#

if anyone would be interested in having a chat in the discord voice channels, id greatly appreciate the help

half eagle
#

good evening, I would like to put some text (the name of the pizza) on a slice with the hover tool, can anyone help me?

#

that's what already happen when i used my mouse on a slice

dire urchin
#

help me tidy up this monstrosity please lol, this is probably the worst solution to the problem but my brain can't think of a better way to do this atm
all I want is to add the "active" functionality to bootstrap's navbar so that the buttons reflect what page you're on - it works but it's so embarrassingly janky lol

#
<li class="nav-item">
    <a class="nav-link active" id="home" href="/">home</a>
</li>
<li class="nav-item">
    <a class="nav-link" href="/projects">projects</a>
</li>
<li class="nav-item">
    <a class="nav-link" href="/contact">contact</a>
</li>
{% if path != "" %}
<script>
    console.log('{{ path }}');
     $(document).ready(function () {
        $('a[id$="home"]').removeClass('active');
        $('a[href$="{{ path }}"]').addClass('active');
    });
</script>
{% endif %} 
#

path is HttpRequest.path[:-1]

dire urchin
#

yeah okay sorry about the above mess, this should make more sense I think (?)

#

I'll go with this for now, but of course if you see me doing something silly here do let me know
I'll just have to split the path string later when I make subdirectories

outer apex
desert cradle
#

I want to use jquery so that the specific div of the web page does not change even if I request the page again. What should I study?

rich shard
#

sorry I'm a noob here
how do i go to a url with the username as the input
what changes should i make here

    <form action="https://twitter.com/" method="get">
      <input type="text" name=""/>
      <input type="submit" value="Search User"/>
    <form>

eg: I type in "elonmusk" and hit submit
and it takes me to this url "https://twitter.com/elonmusk"

night tapir
#

im trying to run some simple code to play around with selenium and ive installed everything required (i think)
im currently running this code

#

but i kep getting this error

outer apex
lavish prismBOT
#

@cerulean badge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

cerulean badge
#

it was a paste.gg link cause the code was a little long

lavish prismBOT
#

@cerulean badge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

cerulean badge
lavish prismBOT
#

@cerulean badge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

normal pebble
#

!paste @cerulean badge

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

cerulean badge
#

ok thanks

thin lance
#

Here is the solution to the problem I was looking for for the search feature in django

from django.db.models import Q

class SearchContact(ListView):
    model = AdressEntery
    template_name = "main/search.html"
    context_object_name = "result"
    
    def get_queryset(self):
        query_input = self.request.GET.get('q')
        result_obj = AdressEntery.objects.filter(Q(name__icontains=query_input),active=True, user=self.request.user)
        return result_obj
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['counter'] = self.get_queryset().count()
        return context
<form action="{% url 'search' %}" method="get">
  <input name="q" type="text" placeholder="Search...">
</form>
final geode
#

In django loading static on a page throws an 500 server error

#

Help lol

native tide
dawn shard
#
@app.route('/ed/<num0>/<num1>/<num2>')
def ed(num0=None, num1=None, num2=None):
  total = num0 + num1 + num2
  return '''
  Addition is ''' + total``` 

It's not really getting added but getting concatenated. How can I add?
vestal hound
#

whether in the route

#

or using a path converter

#

preferably the latter

dawn shard
inland oak
#

which is it framework btw?

#

I am highly sure that returning
return '''
Addition is ''' + total
is not acceptable

#

you should return some sort of Response class with body inside it

#

preferably in json format

dawn shard
#

It worked

inland oak
#
def ed(num0, num1, num2):

None values serve nothing, perhaps to remove it

dawn shard
#

It can concatenate strings not int.

#

so i did this ```py
@app.route('/ed/<num0>/<num1>/<num2>')
def ed(num0=None, num1=None, num2=None):
total = int(num0) + int(num1) + int(num2)
Total = str(total)
return '''
Addition is ''' + Total

dawn shard
stable sentinel
#

Hi there, I hit a wall with Django forms.

I made a contact form that posts an email and it works just fine. does what its supposed to.
However, when I try and include the same form in to my home page the post functionality just stops working

the contact_form.html is as follows...

    {% csrf_token %}
    {{form}}
    <button type="submit">Submit</button>
</form>```

and this works perfectly

but when I include this file in my home.html
#
    {% load crispy_forms_tags %}
    <div class="container">
        <!-- Contact Section Heading-->
        <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Contact Me</h2>
        <!-- Icon Divider-->
        <div class="divider-custom">
            <div class="divider-custom-line"></div>
            <div class="divider-custom-icon"><i class="fas fa-star"></i></div>
            <div class="divider-custom-line"></div>
        </div>
        <!-- Contact Section Form-->
        <div class="row justify-content-center">
            <div class="col-lg-8 col-xl-7">
                {% include 'contact/contact_form.html' %}
            </div>
        </div>
    </div>
</section>```

it does not work
versed python
#

Oh wait you already have them

#

What exactly isn't working?

#

Is the request not being sent?

stable sentinel
#

correct, when posting from home.html it does not post

#

but it does from contact_form.html

#

my forms.py is as follows


    name = forms.CharField(max_length=50)
    email = forms.EmailField()
    inquiry = forms.CharField(max_length=150)
    message = forms.CharField(widget=forms.Textarea)

    def get_info(self):
        """Method returning a formatted string
        :return: subject, message
        """
        clean_data = super().clean()

        name = clean_data.get('name').strip()
        from_email = clean_data.get('email')
        subject = clean_data.get('inquiry')

        msg = f'{name} with email {from_email} said: '
        msg += f'\n{subject} \n\n'
        msg += clean_data.get('message')

        return subject, msg


    def send(self):

        subject, msg = self.get_info()

        send_mail(
            subject = subject,
            message = msg,
            from_email = settings.EMAIL_HOST_USER,
            recipient_list = [settings.RECIPIENT_ADDRESS]
        )

contact/views.py is

from .forms import ContactForm
from django.urls import reverse_lazy

class ContactView(FormView):
    template_name = 'contact/contact_form.html'
    form_class = ContactForm
    success_url = reverse_lazy('contact:success')

    def form_valid(self, form):
        """
            call the custom method of our ContactForm class
        """
        form.send()
        return super().form_valid(form)

class ContactSuccessView(TemplateView):
    template_name = 'contact/success.html'

this is whats rendered in contact_form.html

#

and I am almost sure that I am importing this the wrong way in my home/views.py the wrong way

from contact.forms import ContactForm


def home(request):  
    """"""
    form = ContactForm(request.POST)
    projects = Project.objects.all()
    context = {
        'projects': projects,
        'form': form,
    }
    return render(request, 'home/home.html', context)```
#

the projects render just fine and the view of the form but it does not post

native tide
#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

lusty wigeon
#

I want to make a progress report model which is of 3 types report,invoice and quotation progress.. So How can I make django Model for it.. Because report has own fields, invoice and quotation has their own.. So how can i make django model for it.. I want to make dropdown or radio field for type of progress that is (report, invoice and quotation)...

dire urchin
#

although i think i still have to pass in the path from views.py, doing request.path.endswith('projects') in the template block throws an exception: Exception Value: Could not parse the remainder: '('projects')' from 'request.path.endswith('projects')'

native tide
#

in django how can i fulltext search with a mysql db? do i need to do a raw sql query?

native tide
#

i need help with css

ionic raft
ionic raft
ionic raft
ember adder
#

Does anyone have good recommendations for a client-side library or mechanism to play and record voice in a Django project?

pastel knot
#

how do u batch create using restframework

#

and if the info for the batch create is from an external api where should the fetch requests be defined

native tide
#

I want to create a website with django,
but I don't know what to create the website for. Is there a list of people online anywhere that want a website made for them? Because I have literally no ideas

#

It would have to be a made-up concept

#

which isn't very good, I'd rather do a real-life concept

wraith topaz
#

how I solve this

#

sqlite3.OperationalError
sqlite3.OperationalError: no such table: posts

stray notch
amber grove
wraith topaz
#

this is how my folder looks like

#

@amber grove

thorn igloo
stable sentinel
#

Maybe even document your learning journey

split drift
stable sentinel
# ionic raft You need a functional or class based view to render out the form for each templa...

I found what the my problem was!!
In my home/view.py I am using a TemplateView to render the page,
the TemplateViews need an explicit POST method which I did not have!!!
I had this declared in my contact form/views.py and implied it in my home/views.py.
(boy was this a lesson to remember!!! 😅 )

BTW I would not call what I did in my forms.py as logic, the get_info() method is simply just cleaning up the data. This is something I came across in the docs. Passing in there the send_mail() function from django.core just made me think at the time of writing that it will allow me to keep my views.py a bit more straight forward 🤷‍♂️

As I am new to Django and development in general, is this somehtig that one would label as not the best practice? Or is this a subjective thing at this point?

P.S.

Thanks for answering me, it was a massive help in finding my answer!!

whole sierra
#

could anyone tell me why my django static dir isnt working

#

Settings.py^

#

Template link^

#

error

plucky wadi
#

STATIC_URL = os.path.join(BASE_DIR,'static')

opaque rivet
#

@whole sierra shouldn't the backslashes be forward slashes?

plucky wadi
#

yeah , that too

whole sierra
#

changed.

#

still doesnt work

#

@plucky wadi

#

@opaque rivet

#

i think the weirdest thing is the fact that i never changed any of this...

#

was working perfectly fine this morning

jovial cloud
#

Hello, can anyone suggest the best deployment options for a flask production app that uses elasticsearch?

whole sierra
#

fixed.

stable sentinel
plucky wadi
#

What is the error ?

shrewd mural
#

Dumb question, what is the cleanest way to store methods I'm using ? (for example, I'm using methods that use values in the URL to display a few things on the view, where am I supposed to store them ? I stored them in a file in the same directory than the tests.py, urls.py and so on, but I definitly feel like it's not their place

obsidian mist
#

Question on Flask. Below is a piece of code in my html document.

<script>
    var res = JSON.parse('{{ res | safe }}');
    console.log(res.data);
</script>

How come this ^ works but when I put the middle lines inside the js file thats loaded in the html body

<script type="text/javascript" src="{{ url_for('static', filename='index.js') }}"></script>```it does not
#

With error:

    at JSON.parse (<anonymous>)
    at index.js:34```
#

Does the {{}} have to be only in the html file to be accessible? If there a way to access it in the js file? Please do tag me if anyone has an explanation 😄

warped heart
#

so it just did src='https://my-website.com/static/index.js'

#

you can use the include block and pair it with with context in your script tag

obsidian mist
#

@warped heart What is "that" youre referring to

#

the js file works and loads fine, it just doesnt like {{}} where as the first snippet inside html doc does

native tide
warm igloo
#

Build an MVP clone of some software you currently use. Instagram? Look at the list of Kindling projects. Todo list. Blog. Design an API around some data set. Depend on what type of job you're going for as well.

floral herald
#

in my Django rest framework project, I used Djoser for authentication. I customized my user model. the problem is only email and password are stored, other fields like names are not stored in my database. how can I solve it?

dense cloak
#

how can i store data in cookies using quart

rare lagoon
#

Where's a good place to learn css?

inland oak
limber dew
# floral herald

did you try to use serializers.ModelSerializer?

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
limber dew
floral herald
#

It’s haven’t any views.py . i only used default endpoints of djoser

limber dew
#

did you set on your settings the auth_user_model ?

#
class UserRegistrationSerializer(UserCreateSerializer):
    class Meta(UserCreateSerializer.Meta):
        fields = '__all__'
floral herald
#

Yeah. It’s top of my first picture

floral herald
west arrow
rare lagoon
inland oak
#

I am too torn apart how to answer this question, but I guess yes, yeah.

stable sentinel
# native tide I don't really have any ideas for what to put on my portfolio page though. I do...

Yeah, I feel your struggle... I have been/am struggling with getting good ideas and I have just lately understood how to go about this.

The approach that I am taking is that I do the usual projects found on Medium articles and youtube. Such as a task manager(to do list), blog, photo album etc... These give you good insight on user registration/authentication CRUD functionality, working with REST APIs and the list goes on...
Once you start seeing what you build and how to build it, you will start some ideas of your own...

The struggle is real, I know but you just have to start and pull through the first couple of tutorials. Check out realpython articles on django, there's a good one for a project portfolio. Build that up and hook it up with a free bootstrap template (that's what I'm doing right now) it will be an amazing learning experience!

Just don't rush your self, take it easy and consider the small apps as a project and sooner than you think those projects will turn in to apps of a bigger project.

deft wave
#

Hey guys, I am trying to print out the id from a database but I am not sure why it is not coming through

#

Is it something that you can't print out into the api? Really new to python flask so sorry if it is a straightforward question

#

Should I post the code and the current output?

uneven radish
#

Hi,
I'm building an Blog App using Django and just added the comment functionality on my Posts.
An HTML page will display a Post and all the comments below it. Also, it will display a form to submit a comment on that Post.
Previously, I was fetching the comment form data and saving it to the DB and return the result with context and other things via a render() method.
Now I know when we submit forms we should not return with render but rather with HttpResponseRedirect.
Now I want to that how can I make sure that a user's comment is added on that post? When using render() I was sending a new_comment variable with my context and checking it if its None or contains something later on my template and showing comment added in green color.
Now I can't send my context via HttpResponseRedirect, how to do this after adding comment? I read online and some forum said to use message? Is there any other option? Here's my code:

#
def post_detail(request, year, month, day, post):
    # Gets a post object if found, or return a 404 error
    post = get_object_or_404(
        Post,
        status="published",
        slug=post,
        publish__year=year,
        publish__month=month,
        publish__day=day,
    )

    # Returns the list of all the active comments on a post.
    comments = post.comments.filter(active=True)

    if request.method == "POST":
        # A comment is posted
        comment_form = CommentForm(data=request.POST)

        if comment_form.is_valid():
            # Create a new comment but do not commit it to the database
            new_comment = comment_form.save(commit=False)
            # Assign a comment its respective post
            new_comment.post = post
            # Commit to the databse
            new_comment.save()
            return HttpResponseRedirect(
                post.get_absolute_url()
            )
    else:
        comment_form = CommentForm()

    context = {
        "post": post,
        "comments": comments,
        "comment_form": comment_form,
    }

    return render(request, "blog/post/detail.html", context)
#

Also, I tried using HttpResponseRedirect with reverse() but can't get that to work. So I used that get_absolute_url to return the url of my current post.
Version I tried:

return HttpResponseRedirect(
  reverse("blog:post_detail"),
  kwargs={
    "year": post.publish__year,
    "month": post.pubish__month,
    "day": post.publish__day,
    "slug": post.slug,
  },
)

But this above code returned Reverse for 'post_detail' with no arguments not found.
The URL is matched but the error was there.

#

Please tag me if you have any clue. I'll go offline in some time.

uneven radish
#

Ping

lime umbra
#

how can i use ipc between a running python program and a website

#

i would like to send variables from the python program to the website

stable sentinel
#

Does anyone have any experience with using QR or barcode readers with their django app?

rare lagoon
#

Should I start with django and all that stuff or should I start making a static web page?

#

To get practice with html, css and js and then start with django or flask

lime warren
#

I'd start with flask

#

@rare lagoon

rare lagoon
#

Alright

regal fossil
#

hi folks, does anyone knows how to add class to django form filed in html?
for exapme when we render form

form.field_name
#

so here how we can provide a class name?

obsidian mist
#

Question on Flask. Below is a piece of code in my html document.

<script>
    var res = JSON.parse('{{ res | safe }}');
    console.log(res.data);
</script>
```How come this ^ works but when I put the middle lines inside the js file thats loaded in the html body 
```py
<script type="text/javascript" src="{{ url_for('static', filename='index.js') }}"></script>```it does not, with error:
```Uncaught SyntaxError: Unexpected token { in JSON at position 1
    at JSON.parse (<anonymous>)
    at index.js:34```Does the {{}} have to be only in the html file to be accessible? Is there a way to access it in the js file? Please do tag me if anyone has an explanation 😄
dusk portal
#
    thumbnail=models.ImageField(blank=True,default='default_notes.jpeg',upload_to='thumbnail_notes',validators=[validate_image_file_extension])
#
@login_required
@cache_page(60*2)
def notes_upload(request):
    if request.method=='POST':
        title=request.POST.get('title')
        desc=request.POST.get('desc')
        file=request.FILES('file')
        thumbnail=request.FILES['thumbnail']
        author=request.user
        if ValidationError:
            messages.error(request,'CAN ONLY UPLOAD PDF FILES')
            return render(request,'index/create.html')
        entry=Notes(title=title,desc=desc,file=file,thumbnail=thumbnail,author=author,published_on=datetime.now())
        entry.save()
        messages.success('Notes updated successfully!')
        return HttpResponseRedirect('/')
    return render(request,'index/notes_upload.html')```
#

when i click on thumbnail select button

dusk portal
#

code is ^^

#
<div class="field">
                <label for="thumbnail">
                    Select Thumbnail
                </label>
                <input type="image"  name="thumbnail" class="">
            </div>```
fast lava
#

pls help me

#

in

#

if you know flask

dusk portal
#

Ohk coming

split haven
#

what's wrong with this?

manic frost
#

the documentation doesn't match the implementation

inland oak
uneven radish
split haven
split haven
split haven
#

please have a look at it, it has whole code

inland oak
#

Navigation to the spot :

split haven
split haven
fluid obsidian
#

Anybody by any chance experience with wagtail. I'm trying to figure out what to do to get some sort of sub-menu/hierarchical menu to work. I kinda get mixed feelings- some github issues seems to suggest they aren't supported, yet the documentation/cms make it looks like there, and I'm just puzzled by it.

split haven
#

Let me know if you find the issue in the code @inland oak

inland oak
lavish prismBOT
#

spotify/util.py line 77

response = get(BASE_URL + endpoint, {}, headers=headers)```
inland oak
#

Make your mind and use if, elif, else at least

split haven
#

so i'd just change it put?

#

get request was to fetch the base url and endpoint to make the api request

inland oak
#

U already invoke request with put(

#

U make at least two requests

split haven
#
    if post_:
        post(BASE_URL + endpoint, headers=headers)
    if put_:
        put(BASE_URL + endpoint, headers=headers)

    response = get(BASE_URL + endpoint, {}, headers=headers)
    try:
        return response.json()
    except:
        return {'Error': 'Issue with request'}
#

isnt it already there?

#

for put and post

#

and then lastly the get req

#

i mean using elif or else and doing this is the same thing isnt it?

inland oak
#
    if post_:
        response = post(BASE_URL + endpoint, headers=headers)
    elif put_:
        response = put(BASE_URL + endpoint, headers=headers)
    else:
        response = get(BASE_URL + endpoint, {}, headers=headers)
    try:
        return response.json()
    except:
        return {'Error': 'Issue with request'}
#

at least this

split haven
#

okay let me try that

split haven
#

doesnt work

inland oak
#

except Exception as e:
Return {"error": str(e) }

#

Just read the error

split haven
#

oka lemme try

split haven
# inland oak Just read the error
    if post_:
        response = post(BASE_URL + endpoint, headers=headers)
    elif put_:
        response = put(BASE_URL + endpoint, headers=headers)
    else:
        response = get(BASE_URL + endpoint, {}, headers=headers)
    try:
        return response.json()
    except Exception as e:
        return {"error": str(e)}```
#

like this?

inland oak
#

Nvm

#

U should be able to read the error from console log

#

If your launched server

#

If u did not silent the error higher

split haven
#

you see console.log doesnt show anything when play/pause is clicked

inland oak
inland oak
#

Best practice would be writing unit tests instead of guessing where the error

split haven
#

or is it because of the function i wrote in the js file for the onClick?

inland oak
#

It could be anywhere

#

Without tests you can search for a long time

#

Tests show the place of the error

split haven
#

okay, thankss

inland oak
#

Try working with pytest

#

For back side

#

And check with smth like jest for front side

#

Just checking back should be enough to eliminate 90% of error places though

split haven
#

cool will do

jovial cloud
uneven radish
#

Hi,
I'm building an Blog App using Django and just added the comment functionality on my Posts.
An HTML page will display a Post and all the comments below it. Also, it will display a form to submit a comment on that Post.
Previously, I was fetching the comment form data and saving it to the DB and return the result with context and other things via a render() method.
Now I know when we submit forms we should not return with render but rather with HttpResponseRedirect.
Now I want to that how can I make sure that a user's comment is added on that post? When using render() I was sending a new_comment variable with my context and checking it if its None or contains something later on my template and showing comment added in green color.
Now I can't send my context via HttpResponseRedirect, how to do this after adding comment? I read online and some forum said to use message? Is there any other option? Here's my code:

#
def post_detail(request, year, month, day, post):
    # Gets a post object if found, or return a 404 error
    post = get_object_or_404(
        Post,
        status="published",
        slug=post,
        publish__year=year,
        publish__month=month,
        publish__day=day,
    )

    # Returns the list of all the active comments on a post.
    comments = post.comments.filter(active=True)

    if request.method == "POST":
        # A comment is posted
        comment_form = CommentForm(data=request.POST)

        if comment_form.is_valid():
            # Create a new comment but do not commit it to the database
            new_comment = comment_form.save(commit=False)
            # Assign a comment its respective post
            new_comment.post = post
            # Commit to the databse
            new_comment.save()
            return HttpResponseRedirect(
                post.get_absolute_url()
            )
    else:
        comment_form = CommentForm()

    context = {
        "post": post,
        "comments": comments,
        "comment_form": comment_form,
    }

    return render(request, "blog/post/detail.html", context)
#

Also, I tried using HttpResponseRedirect with reverse() but can't get that to work. So I used that get_absolute_url to return the url of my current post.
Version I tried:

return HttpResponseRedirect(
  reverse("blog:post_detail"),
  kwargs={
    "year": post.publish__year,
    "month": post.pubish__month,
    "day": post.publish__day,
    "slug": post.slug,
  },
)

But this above code returned Reverse for 'post_detail' with no arguments not found.
The URL is matched but the error was there.

marble spire
#

can anyone tell me wh yam i getting error 404 in terminal

#

i added a css file and thats not working

#

plzz help

#

any django developer here

#

?

uneven radish
#

Did you load static in the templates?

#

{% load static %}

marble spire
#

can u check my code

#

yes i did that @uneven radish

stable sentinel
#

OK... I just got a nosebleed cause of this lol, someone please help.

I am rendering some images from a database

    title = models.CharField(max_length=50)
    description = models.TextField()
    technology = models.ManyToManyField('Category', related_name='projects')
    link = models.URLField(blank=True)
    image = models.FilePathField(path='img/')```
where the img/ is under my static directory. Like this my admin panel keeps crashing with a FileNotFound exception cause it can not seem to find the img / directory. If I change the path to static/img than admin panel works well but I get a 404 for the image cause django is looking for it in static/static/img. regardless of what I define there as path it will prefix it with static/

I had the exact same problem a week ago, and all of a sudden it was working with the img/ path. Like, everything worked. Now I added a new item to the DB and its doing the same thing again. 

This is suuuper weird....
#

I found the same issue on stackoverflow from some months back but it has no answer. 🤷‍♂️

dusk portal
#

@marble spire what's the issue my dear

obsidian mist
#

Maybe some better way than jinja

buoyant geode
#

Hi can some one help me with this error Invalid block tag on line 200: 'static'images/home_slider.jpg''. Did you forget to register or load this tag?

buoyant geode
#

style="background-image: url({%static'images/travello.jpg'%})"

#

while doing this I get error

#

I even did {% load static%} and in setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'assets')

native tide
#

what library are you using

charred epoch
#

hey just wanted to ask is it legal to use someone's photo in a website who's popular such as python's founder Guido

buoyant geode
#

Django 3.2.5 @native tide

charred epoch
#

oh sorry

native tide
#

is home_slider.jpg inside of static/ folder

#

@buoyant geode

buoyant geode
#

yeah

#

see when I use static for "{% static 'styles/bootstrap4/bootstrap.min.css'%}" this it works properly but when I use for this style="background-image: url({%static'images/travello.jpg'%})" it throws me error @native tide

native tide
#

though

#

not travello.jpg

#

?

buoyant geode
#

see this error occurs for this type of lines url({%static'images/it-can-be-anything.jpg'%})"

#

and there are few images inside url(....)

#

for every image inside url when I mention static this error occurs

buoyant geode
#

I did this style="background-image: url('/static/images/travello.png')" instead of this style="background-image: url({%static'images/travello.jpg'%})" and it works @native tide

rustic narwhal
#

u wrote {% load static %} ?

buoyant geode
#

yeah I did

rustic narwhal
#

because the error says "Invalid block tag on line 200: 'static'images/home_slider.jpg''. Did you forget to register or load this tag?"

#

so you have not loaded static

buoyant geode
#
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')```
#

@rustic narwhal but it did not worked

#

it worked after style="background-image: url('/static/images/travello.png')" doing this

#

instead of this style="background-image: url({%static'images/travello.jpg'%})"

rustic narwhal
#

try using just like this {% static 'images/travello.jpg' %}

#

try not using url

buoyant geode
#

okay

rustic narwhal
#

did it work ?

buoyant geode
#

No @rustic narwhal

versed lotus
buoyant geode
#

@versed lotus ok

versed lotus
#

what is zip_file?

fleet quest
#

I've tested with other parts of the form (which takes in an excel file) & I'm not able to functions to process as files, not file paths.

versed lotus
#

okay, yea, but what is it? ZipFile expects a path, path-like, or file-like object. what is form.invoice_zip.data then?

fleet quest
#

it's a zip file? I don't know if it's being processed by file name or as a file object.

#

I'm using Flask requests for this.

versed lotus
#

if it's flask, it seems to be some kind of FileStorage object. not a file-like. not sure how to use that. if it's even "file-like" and can be used like that

fleet quest
#

so I'd need to convert FileStorage to a file-like object?

versed lotus
#

maybe, I wouldn't know for sure. Never done it like that.

#

you can use invoice_zip.save( ... ) - see the flask docs how to securely save uploaded files

fleet quest
#

good idea. maybe then I can find out whether it's really storing as an object & not as a file name.

real fossil
versed lotus
#

though correct attribution is often necessary

lyric beacon
#

does anyone know how I can host a simple website with a single image, nothing else

fiery turret
#

this may help

lyric beacon
#

kk

#

I'm using replit

dusk portal
#

hey

#

@eternal blade hey where r u hero

eternal blade
#

Sorry, bit busy rn

dusk portal
#

ohk

marble spire
dusk portal
#
STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static')
    ]```
#

first import os

#

os.path.join(BASE_DIR) this means the root where app the apps nd manage.py is there

#

just create static there

#

and put like this static here is folder name

#

simple and then load static and in each where u wanna load "app.js " to "{% static 'app.js' %}"

#
@login_required
@cache_page(60*2)
def notes_upload(request):
    if request.method=='POST':
        title=request.POST.get('title')
        desc=request.POST.get('desc')
        file=request.FILES('file')
        thumbnail=request.FILES('thumbnail')
        author=request.user
        if ValidationError:
            messages.error(request,'CAN ONLY UPLOAD PDF FILES')
            return render(request,'index/create.html')
        entry=Notes(title=title,desc=desc,file=file,thumbnail=thumbnail,author=author,published_on=datetime.now())
        entry.save()
        messages.success('Notes updated successfully!')
        return HttpResponseRedirect('/')
    return render(request,'index/notes_upload.html')```
#
 <div class="field">
                <label for="thumbnail">
                    Select Thumbnail
                </label>
                <input type="image" name="thumbnail" class="">
            </div>```
#

error iz

TypeError at /notes_upload/
'MultiValueDict' object is not callable```
opaque rivet
#

@dusk portal request.files is a MultiValueDict, it's not a callable.
Access files via request.form['form_name'] instead of calling it request.form('form_name')

opaque rivet
# dusk portal ```py STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ]```

This is incorrect. STATICFILES_DIRS CANNOT include the STATIC_ROOT. STATIC_ROOT = where staticfiles are collected when you collectstatic.
STATICFILES_DIRS = the locations of staticfiles to be placed in the static root when you collectstatic. This cannot include the static root.

Also when you use the static tag in your jinja2 template, it has nothing to do with your static root or static dirs - that uses your static URL.

dusk portal
#

;_;

#

He's asking this
simple and then load static and in each where u wanna load "app.js " to "{% static 'app.js' %}"

#

See my whole answer

marble spire
#

can i share my screen and can u check the code and find out the mistake

dusk portal
#

What u wanna do load the css and js files that are already in ur device ?

marble spire
#

@dusk portal

dusk portal
#

Sure

marble spire
#

thanks

opaque rivet
#

@dusk portal cool, apart from the fact it doesn't really make sense what you're saying, the static tag uses STATIC_URL.

@marble spire Have you added a path to serve your staticfiles in urls.py?

marble spire
#

hold for a moment

opaque rivet
#

@marble spire Have you added a path to serve your staticfiles in urls.py?

dusk portal
#

He himself too is confused what he wanna do

opaque rivet
#

Well, let's see some relevant code then.

dusk portal
#

Do u code at Angular too?

marble spire
marble spire
dusk portal
marble spire
dusk portal
#

Yes u r right too

#

Don't leave stick with it

#

Just tell me the issue

marble spire
#

which vc to join

opaque rivet
#

@marble spire show relevant code, like you said?

marble spire
#

soo

#

it s done

opaque rivet
#

👍 Good to hear

marble spire
#

👍

wraith prawn
#

Hi guys, not sure if this is a python issue or html, trying to pass a dictionary to HTML, but when I try to pass it with {{ stashData | tojson | safe }} I just get null, any thoughts pls?

limber trellis
#

hey guys someone here ?

#

i need a help with django

fiery turret
#

Is there some way to differentiate between a string and a list in Jinja

#

I have some entries that are strings and others that are lists of strings and, to my knowledge, jinja doesnt have a way to do type checking.

wraith topaz
#

flask or django

mystic wyvern
native tide
#

@versed lotus are you able to dm me

fiery turret
ionic raft
# wraith topaz flask or django

Depends 🙂
Flask got me off to a great start. Been working solely in Django for 2 months.
How complex is the web project?

terse vapor
#

I'm trying to use bs4 to scrape from indeed, base on the job offer, i want to scrape the detail of the job, but the link id are based on the job_id, so is there a way for me to solve it?

frank shoal
#

Does indeed have a public api you can use instead?

rustic sky
#

Django help
So my app is being served over HTTPS and everything is verified works as it should.
using the deployment check, I got a warning about SECURE_HSTS_SECONDS. As a person that's kinda new to all this (although I made sure my site never serves expired certificates with certbot auto renewal) what should I set this to?

rotund kestrel
#

Guys I want to deploy a A* Visualized python application and I will be using flask

#

However for making the a* Visualiser the Tutorial I'm referring uses pygame

#

So either I have to use some other library , or find a way to integrate pygame into flask ,which from what I read is not possible

wraith topaz
#

this is for me

#

cause I want to make my opencv projects run on my phone

dusk portal
#
@login_required
@cache_page(60*2)
def notes_upload(request):
    if request.method=='POST':
        title=request.POST.get('title')
        desc=request.POST.get('desc')
        file=request.FILES['file']
        thumbnail=request.FILES['thumbnail']
        author=request.user
        if ValidationError:
            messages.error(request,'CAN ONLY UPLOAD PDF FILES')
            return render(request,'index/create.html')
        entry=Notes(title=title,desc=desc,file=file,thumbnail=thumbnail,author=author,published_on=datetime.now())
        entry.save()
        messages.success('Notes updated successfully!')
        return HttpResponseRedirect('/')
    return render(request,'index/notes_upload.html')```
#
MultiValueDictKeyError at /notes_upload/
'thumbnail'``` still
#

no error is coming in file

#

it's coming in thumbnail

thorn igloo
wraith topaz
#

how can I make this into a list going down insted of sideways html <button style="background-color:red; border-color:blue; color:white";margin-left:auto; margin-right:auto;display:block;margin-top:5%;margin-bottom:0%"> DOCUMENT SCANNER </button> <button style="background-color:red; border-color:blue; color:white";margin-left:auto; margin-right:auto;display:block;margin-top:5%;margin-bottom:0%"> ANGLE FINDER </button> <button style="background-color:red; border-color:blue; color:white";margin-left:auto; margin-right:auto;display:block;margin-top:5%;margin-bottom:0%"> QR READER </button> <button style="background-color:red; border-color:blue; color:white";margin-left:auto; margin-right:auto;display:block;margin-top:5%;margin-bottom:0%"> FINDING DISTANCE </button> <button style="background-color:red; border-color:blue; color:white";align-items:"center";margin-left:auto; margin-right:auto;display:block;margin-top:5%;margin-bottom:0%"> AUGMENTED REALITY </button>

sweet helm
west arrow
#

How do I make a form from the serializers field using api_view(Fbv) on the browsable API page

tropic trout
#

Hi, anybody using FastAPI?

#

I have a test server running, now I want to implement a "shutdown" API, when the server receives this API, it should quit the execution (i.e. process exit), is this possible?

opaque rivet
#

@dusk portal that is an error coming from your files, because the only time you mention thumbnail is accessing the files.

#

I'd debug the view to see if it's actually receiving the file data. Note that your request containing file data must have the content type multipart/formdata

dusk portal
#

Ig Problem isnt in my view
Or model as when I'm doing same thing from admin panel it's working

#

Problem is in the html

dusk portal
#

Yes I'm 101% I have that

opaque rivet
#

I would check the view to see what files it's receiving.

mystic vortex
#

@opaque rivet Hey bud I need help once more

#

How to make a Http request to the backend, I mean I am using a api to transfer some dataa from dashboard but whenever the data is uploaded in the api how can will my backend know that some data has been uploaded?

velvet yew
#

How can I troubleshoot why is my Django API's response time awful when doing authentication? I've got a simple endpoint for testing that goes like:

@api_view(["GET"])
@authentication_classes([BasicAuthentication, SessionAuthentication])
@permission_classes([IsAuthenticated])
def test(request):
    if request.method == "GET":
        data = {"user": request.user}

        return JsonResponse(
            data=data,
            status=200,
            json_dumps_params={
                "default": str,
                "ensure_ascii": False,
                "indent": 2,
            }
        )

I'm getting ~50 ms response time when commenting out the authentication classes, but 1.5 - 2.5 sec when I'm using authentication. The DB has a response time of around 25 ms from where I run the web server (locally for now)

eternal oxide
mystic vortex
#

How can I get a value from my html to my python script

opaque rivet
#

@velvet yew simply because the authentication class adds extra middleware. 50ms is good.

#

@mystic vortex I don't know what you're trying to ask. Do you want to log your API requests?

velvet yew
opaque rivet
#

Oh I misread!

#

@velvet yew does removing BasicAuthentication class help anyhow? I don't see you using that anyway.

#

Because your request will go through that middleware first before session auth.

velvet yew
#

Oh let me try I just added it because the guide said so

#

It does make is fast but then I can't authenticate anymore

#

And I get {'detail': 'Authentication credentials were not provided.'}

#

So I guess it's fast because it fails lol

rustic sky
#

Hi. How can I make sure Search engines don’t list my admin panel?

#

Robots.txt is a bad idea, because then the hidden url is exposed

inland oak
#

or even restrict access with ip white list

#

at nginx or iptables level

#

you can forbid exact urls beginning in both cases

rustic sky
cerulean laurel
#

why am i keep having json { "detail": "Method \"GET\" not allowed." } whenever i use postman to create a product

inland oak
#

you need to make highly likely POST request

vestal hound
#

^

inland oak
#

GET requests can't upload json data

vestal hound
#

if you don't, this would be a really good time to learn

rustic sky
#

Just realized I didn’t mention django admin panel to begin with

inland oak
#

it will work almost literally with everything

#

if we have nginx in reverse proxy mod

opaque rivet
#

@velvet yew hmm, so which method are you using to authenticate? Basic auth?

inland oak
#

and that's how I covered django admin panel

velvet yew
cerulean laurel
#

@vestal houndyeah yeah my bad, i forget the GET in postman ..

#

well..

sharp breach
#

hey guys
hellp me

I want to place google map below the discord username how should I do??
?

cerulean laurel
#

CSS FLEX BOX

sharp breach
#

how should I do that

#

do u want to see google map code

#

?

lavish prismBOT
#

Hey @swift glen!

It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.

Feel free to ask in #community-meta if you think this is a mistake.

cerulean laurel
#

@sharp breachhttps://code2care.org/pages/how-to-place-two-div-elements-next-to-each-other#:~:text=If%20you%20want%20to%20place,use%20a%20CSS%20property%20float.&text=As%20the%20name%20goes%20the,left%20w.r.t%20to%20its%20container

Code snippets for : How can we place two div tag elements next to each other using css.

swift glen
#

goodevening guys. I've been stuck for a week trying to send a simple email using python django and angular as a front end. stackoverflow had no clear answer for this. any idea how to do it guys?. here's my own code btw

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @swift glen until <t:1631539093:f> (9 minutes and 59 seconds) (reason: attachments rule: sent 8 attachments in 10s).

quiet solstice
#

!unmute 715204879857090681

lavish prismBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @swift glen.

quiet solstice
#

please check out

#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

sharp breach
#

its not working

#
                <div class="mapouter"><div class="gmap_canvas"><iframe width="511" height="277" id="gmap_canvas" src="https://maps.google.com/maps?q=2880%20Broadway,%20New%20York&t=&z=13&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" 
                    marginheight="0" marginwidth="0"></iframe><a href="https://123movies-to.org">123movies</a><br><style>.mapouter{position:relative;text-align:right;float:right; height:277px;width:511px;}</style><a href="https://www.embedgooglemap.net">google map api for website</a><style>.gmap_canvas {overflow:hidden;background:none!important;height:277px;width:511px;}</style></div></div>
            </div>```
#

look at line 5

#

I have added

#

float right

#

and also tried to do it in css.map_wrapper{ float: right; }

#

@swift glen

#

what should I do??

native tide
#

student table
->Name
->rollno pk
->age
->school Foreign key of school table

School table
->Name:zzz
->id:101
->“location:paris
->branch:c15

student
{
“name”: “Abc”,
“rollno”:12,
“age”:14,
“school”:{“Name”:”zzz”,
“id”:101,
“location”:”paris”,
“branch”:”c15”
}
}

how can i get the output like above json output, like to create a dictionary output for foreign key linked table
in Django

like school table dictionary in above output

swift glen
dense slate
#

Especially if you can't allow just certain IPs.

dense slate
#

You can create a serializer, if that's what you're wondering?

#

To convert an object to JSON.

native tide
#

yes , but i need to get foreign key table details for specific field
i.e in that output ,student field got every detail from school record

#

fetch student school record from School table as result for that field

north bluff
#

guys is there like a front end framework for python?

#

like, html but python based

#

I'm learning django atm, and there's mostly backend stuff

#

and some html for frontend

#

maybe there's something like GrapesJS but for python yk

dense slate
#

Even if there is one I expect it would be a very hacky way to do things.

north bluff
#

f alr

inland oak
#

it will appear in advance before the admin panel, moderators only will need to write correct password, before they access admin panel where they will properly authentificate as second step

#

whilisting ip is required for more... thorough defense

#

we could white list all ips from our company network

#

in one line/rule

#

something like....
Allow 165.65.0.1/16, if I wrote it correctly

#

will allow all ip addresses from 165.65.0.1 to 165.65.255.255 range

#

or actually even better.

#

we could allow only access to servers, from computers which have enabled our private company VPN 😉

#

which could connect only from company network ;b

dusk portal
#

Wow

#

Pro

azure pine
#

@inland oak you opened my mind through this.

#

any ssas or opensource tool to get this done ?

inland oak
#

a bit of eyeing wireguard, tried that before. rumours say it has 20 times less overbloaten code

azure pine
#

awesome i heard about it before getting into coding, great stuff

inland oak
#

a bit of silly instruction tbh, since it is using shell language for all of it to run

#

bit at least it is user friendly

azure pine
#

thanks buddy

native tide
#

how do i update a part of the html without refreshing the page? do i need a api that send a json with data that i want and then js magic to update the html?

solar fulcrum
#

hi. anyone available to point me to a direction for a django project? just general question, no code help.

#

more like.. a conceptual question.

rare lagoon
#

Is there a way the image doesn't separate the paragraph and the h1? I moved the image to the right with margin-left

#

Like that

desert estuary
#

i had a prob

class Students(db.Model,UserMixin):
   id=db.Column(db.Integer(),primary_key=True)
   fullname=db.Column(db.String(50),unique=True,nullable=False)
   email=db.Column(db.String,unique=True,nullable=False)
   personal_email=db.Column(db.String,unique=True)
   password=db.Column(db.String(),unique=True,nullable=False)
   dialling_num=db.Column(db.String(),unique=True)
   branch=db.Column(db.String())
   occupation=db.Column(db.String())
   company_name=db.Column(db.String())
   linkedin=db.Column(db.String())
   github=db.Column(db.String())
   website=db.Column(db.String())

   def __init__(self,fullname,email,personal_email,password,dialling_num,branch,occupation,company_name,linkedin,github,website):
      self.fullname=fullname
      self.email=email
      self.personal_email=personal_email
      self.password=password
      self.dialling_num=dialling_num
      self.branch=branch
      self.occupation=occupation
      self.company_name=company_name
      self.linkedin=linkedin
      self.github=github
      self.website=website

and later on when i was adding people into the database so they can be recognized by the platform, i added none on the last 4 company linkedin github and website cuz there are info that the user will add in and not us
but when i went to the platform and did wanna do some updates it didn't update a thing

#

here's some dummy data that i wanna update

#

as you can see it didn' tupdate the branch and occupation

#

please anyone knows why

#

https://pastecord.com/isehuqiwij.sql i had an issue before this tho
i was adding users to the table and for the stuff that should be added by them i left it blank for instance
company_name=""

ionic raft
# native tide how do i update a part of the html without refreshing the page? do i need a api ...

There are at least three ways to do this that I am aware of:

  • AJAX. I've not personally worked with AJAX, but it has been around for a number of years.
  • JS: This is definitely a candidate for managing page behaviour. I'm getting ready to work with JS, researching a Framework currently. However, so far I've used the following...
  • HTMX: I've been working with this tech recently. It only has a couple of lines to call the JS script (just as you would for a css framework such as bootstrap/tailwinds). You can then invoke all sorts of tricks to update partial pages. The documentation is solid. I'm using it in a couple of instances in a Django web application to amazing effect. There is no script overhead that I can observe, and it results in really fast DB updates. In short, I'm astonished at how effective HTMX is. If you want to see it in action DM me.

Whatever the case, both the above methods can be researched to deliver what I believe you are looking for.

manic frost
#

AJAX is just a fancy acronym for 'asynchronous HTTP requests'

native tide
#

How can I access an ng-input combobox with its dropdown values inside a ng-select listbox?
I'm using selenium webdriver
Or do you need the whole dom structure to tell?

#

its an angular based website

#

its a dropdown menu

stray notch
#

is there something like django-q, but for flask? (ie. pip installable, all python)

dense slate
#

Like RabbitMQ?

#

or redis

#

I think those two are agnostic.

stray notch
#

rabbitmq uses erlang, which isn't an option. needs to be python

dense slate
#

Redis is in C at least... why does it have to be written in python?

stray notch
#

I'm running it on pythonanywhere, which is limited

dense slate
#

Limited how?

stray notch
#

I think you can use redis as a broker for django-q

stray notch
dense slate
#

I see. Are you using the free tier? You an get a linux server for $5/month on DigitalOcean. Having those kind of limitations seems like a huge PIA.

stray notch
#

haha. Agree.

#

thanks @dense slate will consider other options :)

dense slate
pliant pelican
#

Anyone able to help me with my website?

alpine tendon
#

Hello

#

I just completed html and css and js so can i join python now

pliant pelican
#

For some reason my website doesn't change the grid item width for when its less than or equal to 574px, it works for the 768px one. Don't really know why.

@media(max-width: 574px){

    .toggle-button{
        display: initial;
    }

    .collapse{
        max-height: 0;
        overflow:hidden;
        transition: all 0.7s cubic-bezier( .42, 0, .58, 1 );
    }

    .collapse .nav-link{
        display: block;
        text-align:center;
    }

    .search-box{
        border-right:none;
    }
    
    .grid .grid-item{
        width: calc(100% - 18px);
    }
}

@media(max-width: 768px){
    .grid .grid-item{
        width: calc(50% - 18px);
    }
}
alpine tendon
alpine tendon
pliant pelican
#

no worries i figured it out

dusk portal
#
    title=models.CharField(max_length=60,blank=False,null=False)
    subject=models.CharField(max_length=50)
    desc=models.TextField(blank=True)
    thumbnail=models.ImageField(blank=True,default='default_notes.jpeg',upload_to='thumbnail_notes',validators=[validate_image_file_extension])
    file=models.FileField(blank=False,null=False,upload_to='Notes',validators=[FileExtensionValidator(allowed_extensions=['pdf','doc','docx'])])
    author=models.ForeignKey(User,on_delete=models.CASCADE)
    published_on=models.DateTimeField(auto_now_add=True)
dusk portal
# opaque rivet I'd debug the view to see if it's actually receiving the file data. Note that yo...
<main id="upload">
        <div class="title">
            Upload Notes
        </div>
        <div class="error">
            error messege here
        </div>
        <form method="POST" enctype="multipart/form-data" >
            {% csrf_token  %}
            <div class="field">
                <label for="title">
                    Title
                </label>
                <input type="text"  name="title" placeholder="video's title" required name="title">
            </div>


            <div class="field">
                <label for="description">
                    Description
                </label>
                <textarea name="description" name="desc"  id="" cols="30" rows="10"></textarea>
            </div>
            <div class="field">
                <label for="video">
                    Upload Notes
                </label>
                <input type="file" required  name="file" accept="pdf/doc,docx" name="Video" class="">
            </div>
            <div class="field">
                <label for="thumbnail">
                    Select Thumbnail
                </label>
                <input type="image" name="thumbnail" class="">
            </div>
            <br>
            <button class="submit">Upload</button>
        </form>
</main>```
naive crater
#

heyo, anyone know if there's an easy way to use the height of an element for another setting in that element?

#

dunno how to word this really, but my use case is using the height of the element as the margin.

#

I'd be happy to elaborate if needed

calm plume
naive crater
#

yeah I just decided to do it in js

#

cuz I'd have to use js to set the css variable anyways

#

for my use case

gritty sky
#

heya

#

im sending a request to a site, and im currently using a session (requests.Session()), and im assigning it headers

#

however when i print the headers, its not printing the ones i assigned it

#

as i say that it works BRUH

harsh helm
#

I dunno if this is the right place but is there anything unique about Firefox Developer Edition?

harsh helm
rustic sky
#

👍

#

okay, different issue

#

now my django admin page is not found

#

@inland oak

inland oak
rustic sky
#

also my auth_basic thing isn't showing, interestingly enough

#

ok

inland oak
#

we can't help if we can't see your code

rustic sky
#
 location /admin_url {
        auth_basic "Restricted territory by website owner";
        auth_basic_user_file /etc/apache2/.htpasswd;
    }
#

the password works and all

inland oak
#

a bit more full config file

inland oak
rustic sky
#

there's gonna have to be a lot filtered out, but okay

rustic sky
inland oak
#

use code highlighter

nginx
rustic sky
#
server {
    server_name [removed];

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/django/projectfolder;
    }
    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
    location /admin_url/ {
        auth_basic "Restricted territory by website owner";
        auth_basic_user_file /etc/apache2/.htpasswd;
    }

well, that's most of it
the rest is just certbot stuff

inland oak
#
server {
    server_name [removed];

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/django/projectfolder;
    }
    location /admin_url/ {
        auth_basic "Restricted territory by website owner";
        auth_basic_user_file /etc/apache2/.htpasswd;

        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
    
#

how about having this

rustic sky
#

okay, now I got my admin page back

#

still gotta test that message though

#

yeah either it's not showing, or it's my browser

inland oak
#

you can't insert correct username/password?

rustic sky
#

oh I can

inland oak
#

it is not accepting them?

rustic sky
#

it is

#

it's the message I'm inda worried about

#

well that's interesting, it shows on my iPad

#

I'm gonna guess because of cache

inland oak
#

why are you worried about the message

#

yeah, test with freshly reopened incognito browser

#

clean from cache by default

rustic sky
#

well it ain't showing there either, but whatever

#

I know it at least works

#

I kinda feel like combining it with specific IP access, but my IP is dynamic and I'm not always home

so that... nah

#

well, thanks man

rustic sky
#

now, I don't have to worry for a while

that's basically everything I needed to take care of

inland oak
#

just in case, you can allow pass with IP or password being right

#
location / {
      satisfy any;

        allow 217.115.32/24;
        allow 127.0.0.1;
         deny  all;

        auth_basic           "You shall not pass!";
        auth_basic_user_file /etc/nginx/htpasswd;
  }
#

in this way

#

satisfy any; makes allowing if at least one of the rules were pased

rustic sky
#

mhm, lol

#

noted!

#

this project took longer than I wanted it to, but at least I didn't rush and possibly make an error (I made sure I didn't)

inland oak
#

I have a project I am working on already a year %

rustic sky
#

now I'm kinda "burnt out" from it for a while, so I'm just gonna leave it running for a bit before I start making the changes

rustic sky
#

mine took a few months on and off

inland oak
#

yeah, it is a bit big one.

rustic sky
#

more off than on tbh

inland oak
#

it is meant for infrastructure of 200+ servers at minimum

#

and at the same time they hired just one developer

#

for everything 😐

#

I am not picky I guess while I am just learning stuff

rustic sky
#

oh god

#

that's a lot for one person

#

I was just creating my website

#

yeah that's a lot (maybe too much)

inland oak
#

it is a good learning experience at least

#

learning, learning, applying at practice, applying at practice

rustic sky
#

oh yeah, for sure

#

sorry, was just doing absolute finishing touches

wraith topaz
#

I need to colour my background white and then make my words light pink

#

I have tried the background element but it didnt work

lavish prismBOT
#

Hey @wraith topaz!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

wraith topaz
#

cant past it its too long

#

but

#

this is a update

#

error

#

if I add thishtml <section style="background-color: black; padding-top: 114.375px;" data-test="page-section" data-section-theme="light" class="page-section to my section which for me I think is the whole background and run it it does nothing

#

thats just one part of the section

#

there is only one section

#

@glacial moat

#

NVM I GOT IT YES

lavish prismBOT
#

Hey @thin lance!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

thin lance
#

Hello, I need help in django conform delete

what i want to do is show the user the option "yes" or "no" when deleting a contact

  1. yes = delete contact
  2. no = return to contact list - i know there is this back option (window.history.go(-1);)

my template conform_delete.html:

    <div class="form" style="text-align: center;">
        <h2>Are you sure you want to delete the "<b>{{ obj.name }}</b>" contact?</h2>
        <!-- <form action="/api/contact-list/" method="POST" novalidate class="test">
        
            {% csrf_token %}
            <br><a href="{% url 'contact-list' %}"><input class="btn btn-success" id="yes" name="yes" type="submit" value="Yes"></a>
        </form> -->
        <a href="{% url 'contact-list' %}"><input class="btn btn-success" id="yes" name="yes" type="submit" value="Yes"></a>

        
    </div>

my views.py:

class DeleteContact(DeleteView):    
    model = AdressEntery
    context_object_name = "obj"
    template_name = "main/adressentery_confirm_delete.html"
    success_url = reverse_lazy("contact-list")  # this is redirected to a specific url for the parameter using the name expressed in urls .py   
    def dispatch(self,request, *args, **kwargs):   #this method allows us to use methods such as (post, get, put ..) and allows us to return HTTP methods such as (response, redirect)
        return super(DeleteContact, self).dispatch(request)  #dispatch method will override the second method and allow us to do redirection
        #return redirect('/api/contact-list/')   #render(request, self.template_name, {})
    def get_queryset(self, *args, **kwargs):
        queryset = super(DeleteContact, self).get_queryset()
        queryset.filter(id=self.kwargs['pk']).update(active=False)
        return queryset   # filter by clicked contact card get id and set active false
#

note: I don't want to delete my object, I set the flag acticve = false.

If I put a button in the form, the contact object in the database is deleted,
but without the form just by clicking on the previous delete link leading to conform_delete, my contact is instantly set to active = false so this button only does redirection.

versed python
#

is get_queryset even called?

#

i dont think it would be

thin lance
stable sentinel
#

Hi, I need a bit of help. I have a model, that contains a FilePathField(path='img/') for which the path should be static/img/
though in this form my admin page raises a FileNotFound exception. If I change path to static/img/ than admin page works fine but, django keeps looking for file in static/static/img/
I am not sure why this keeps happening. I found this question being asked on django forum and stackOverflow but they have no answers...

versed python
versed python
#

Set it to "static"

#

Though i would advise against it since the static folder is not for user uploaded content

thin lance
#

how am I supposed to do this?

versed python
stable sentinel
#

this won't be something that's uploaded by users. These will be images served by my website for each project. I figured to use this way so that I don't have to hard code images to my HTML

mystic vortex
#

i need help

stable sentinel
#

is this a good way of doing it?

mystic vortex
#

someone help plz

#
from flask import Flask, jsonify, render_template
from threading import Thread
app = Flask(__name__)



@app.route('/')
def home():
    return render_template("main.html")

@app.route("/dashboard")
def dashboard():
    demo = "discord"
    return render_template("dashboard.html", demo =  demo)






def run():
    app.run(host='0.0.0.0',port=1)

def keep_alive():
    t = Thread(target=run)
    t.start()





if __name__ == "__main__":
    app.run(debug = True)
    
keep_alive()
#

this is not starting the web server with 0.0.0.0 host

raw compass
#

whats the error

mystic vortex
#

no error

#

its just not starting

#

making the server with a different host

#

127.0.0.1:5000

raw compass
#

Sorry whats happening when you do 127.0.0.1:5000

mystic vortex
#

This site can’t be reached127.0.0.1 refused to connect.

#

i want a 0.0.0.0 host

raw compass
#

port 1 might be special

use 58432 a random large number

#

below 64000

mystic vortex
#

but its making with 127.0.0.0:5000

raw compass
#

0.0.0.0 is not a host. Its a network

mystic vortex
#

ye i mean that

#

but how can i get that

#

@raw compass

raw compass
#

I'll check and run your code.

glacial yoke
#

I have some info callback in the GET request on my localhost, but whenever i try to do request.GET to get the results of the info callback, I get Attribute error, object has no attribute GET

#

how can I get that info?

mystic vortex
#

@raw compass i got a error

raw compass
mystic vortex
#

i fixed it

#

@raw compass

#

sry for ping but need help

#

i want to run in 0.0.0.0 but its not running in it

raw compass
#

you still need to put in 127.0.0.1 in the browser

#

or get your IP address and that should work on your network as well (depending on firewall)

mystic vortex
#

if __name__ == "__main__":
    app.run(debug = True, host='0.0.0.0',port=random.randint(2000, 50000))
    
mystic vortex
raw compass
mystic vortex
#

what??

mystic vortex
raw compass
#

you have made a run function and you were not using it

mystic vortex
raw compass
#

thats why in your most recent example you needed to change it.

Yes your most recent example makes sense

Though you may as well delete your def run(): function

mystic vortex
#

not working till now @raw compass

#

still not 0.0.0.0

#
from flask import Flask, jsonify, render_template
from threading import Thread
import random 
app = Flask(__name__)

@app.route('/')
def home():
    return render_template("main.html")

@app.route("/dashboard")
def dashboard():
    demo = "discord"
    return render_template("dashboard.html", demo =  demo)





def run():
  app.run(host='0.0.0.0', port=random.randint(2000, 50000))





if __name__ == "__main__":
    run()
#

its still not 0.0.0.0

echo summit
#

0.0.0.0 means the program accepts connections for all IPs it can handle

#

As opposed to specifying the ip

mystic vortex
#

yea i want that

echo summit
#

But 0.0.0.0 is still not a valid ip

mystic vortex
#

how can i get that '

echo summit
#

You need to use either local host or 127.0.0.1

#

(In your browser or whatever you’re using)

mystic vortex
echo summit
#

You can’t

#

0.0.0.0 is reserved as a placeholder

mystic vortex
#

so how an i accept response from everyone

#

i am making a dashboard

raw compass
#

When I run your code

 python discord_flask_wildcard.py
\ * Serving Flask app 'discord_flask_wildcard' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://192.168.0.4:31186/ (Press CTRL+C to quit)
echo summit
#

So if you have 0.0.0.0 in you config the program will accept connections for all ips the pc has

echo summit
#

That is usually local host (127.0.0.1) and all ips that are assigned

mystic vortex
#

?

#

i want to make it 0.0.0.0

echo summit
#

Wdym make it 0.0.0.0

#

You want to use 0.0.0.0 in your browser to connect?

mystic vortex
#

cause i am making a bot dashboard

echo summit
#

Yes that means you need an IP address that is reachable from the internet

mystic vortex
echo summit
#

Then you specify 0.0.0.0 in your config and the program will accept all connections regardless of the ip used to connect to the program

mystic vortex
#

i am new to web dec

#

dev

#

i just started a day ago

echo summit
#

So let’s say your server has access to 2.3.4.5

mystic vortex
#

ok

echo summit
#

That means that traffic for that ip is sent to your server

#

Then the program will accept connections if users use that ip to connect

mystic vortex
#

i am trying to make it accept all requests but no its not accepting

#

its only accepting from me

echo summit
#

What ip are you using to connect?

echo summit
#

ok, so where are you running the porgram?

grave raft
#

My production server uses gunicorn where can I see print statements???

echo summit
#

what command are you using to run gunicorn

#

but by default gunicorn doesnt print or log print statements

tough crane
#

Hey there, wanted to quickly ask if I (via django for-loops) generate Id's for Div elements. I can not target them via css/scss right? I have to do it via JS ?

echo summit
#

why do you want to do that in the first place

#

ids and classes are mainly there to identify their css style

#

if you want a unique id for targeting them in js code you can add an additional id or class

tough crane
#

I want to change the color of some of them. Because some of them have different backgrounds so in order for them to be readable nicely, they need to have different text colors.

#

Like if you see here, the second one is very badly readable. So I want to change the text color of it.

echo summit
#

are the images predetermined or do they change

#

also you can do inline styles

tough crane
#

Everything is loaded from a Database. So the image always stays the same.

echo summit
#

then why bother generating ids

#

just make two ids and style them independently

#

or make a general style and then add an inline style like this:

#
<h1 style="color:blue;">A Blue Heading</h1>```
tough crane
#

The id's are generated automatically because there is a for loop that is generating the elemente.

#

i can not add inline styling

#

That's the code that generates these two images (cause there is only two right now).

echo summit
#

then you could add the colour you want to the portfolio object and add that to the repeating template

tough crane
echo summit
#

you could do a default color

#

like py {{portfolio.colour if portfolio.colour else "#fff"}}

#

that means that if the colour is set it uses that colour else it uses the default

tough crane
#

ahh I see. that could be helpfull. Thank you ❤️

regal fossil
#

hi there I am using django LoginView to login a user and on invalid credential it is not showing any error

regal fossil
#

i tried

{% if messages %}
{% for message in messages%}
  {{ message }}
{%endfor%}
{%endif%}

but its not working

echo summit
#

is that the whole template?

regal fossil
#

no i am using default and login

echo summit
#

can you show the whole file/template?

regal fossil
#

this is default

#

login template

#

views using built in LoginView

echo summit
#

they will just add the text to the html but it will just be ignored

regal fossil
#

so how i show the errors here if users credentials are invalid

thorny flower
#

Hey, I want to store the _Rolename in a separate variable as a property (string) then what should I do ?

class Roles(models.Model):
  _RoleName = models.CharField(max_length=80)

  @property
  def RoleName(self):
    return self._Rolename  # Is this correct? 
echo summit
thorny flower
regal fossil
tough crane
#

And then in your views you will need to add a message object. Like this for example.

#

Now in my template the message "your profile has been updated" will appear.

regal fossil
tough crane
regal fossil
#

how ?

tough crane
regal fossil
#

Thank you I just found the problem but I will look it as well
I am using my own forms so they dont have that functionality to show errors
thats why I am not seeing errors

tough crane
#

ah but you can just ask is form valid normally if it builds on a default form. If not then ye you gotta build that in.

regal fossil
#

yeah

tough crane
#

but I'm sure you find something. Django has lots of answers

upbeat umbra
#

I am trying to handle email confirmations and I keep getting this error in flask-mail

#

Anyone knows a way I could fix this? Perhaps I am missing something?

dusk portal
#
@login_required
@cache_page(60*2)
def notes_upload(request):
    if request.method=='POST':
        title=request.POST.get('title')
        desc=request.POST.get('desc')
        file=request.FILES['file']
        thumbnail=request.POST.get('thumbnail')
        author=request.user
        if ValidationError:
            messages.error(request,'CAN ONLY UPLOAD PDF FILES')
            return render(request,'index/notes_upload.html')                 
entry=Notes(title=title,desc=desc,file=file,thumbnail=thumbnail,author=author,published_on=datetime.now())
        entry.save()
        messages.success('Notes updated successfully!')
        return HttpResponseRedirect('/')
    return render(request,'index/notes_upload.html')``` this is my code which integrates and send post request from the frontend side
#
class Notes(models.Model):
    title=models.CharField(max_length=60,blank=False,null=False)
    subject=models.CharField(max_length=50)
    desc=models.TextField(blank=True)
    thumbnail=models.ImageField(blank=True,default='default_notes.jpeg',upload_to='thumbnail_notes',validators=[validate_image_file_extension])
    file=models.FileField(blank=False,null=False,upload_to='Notes',validators=[FileExtensionValidator(allowed_extensions=['pdf','doc','docx'])])
    author=models.ForeignKey(User,on_delete=models.CASCADE)
    published_on=models.DateTimeField(auto_now_add=True)
#

this is my model

#

so when im filling the form it's like raising error that i provided in Validation error message

#

after filling the form

#

im choosing .pdf file

#

then too

shut siren
#

anyone wanna make a website together?

glacial yoke
vapid shoal
#

Can anyone tell me why this doesn't auto download when I click the button? In both Firefox and Chrome, nothing happens. This is a valid FTP link and I want to be able to click the button and it auto download, which is what I read the download tag is for. Is something wrong here?
<a class="btn btn-info btn-sm" download href="ftp://myuser:password@hostname/path/to/file/File.zip"></a>Click to Download</a>

buoyant geode
#

Hi some one please help me with is I am trying to use and I'm using Django redirect when I am at http://127.0.0.1:8000/travello/accounts/register/ return redirect('travello/') but it is redirecting to http://127.0.0.1:8000/travello/accounts/register/travello/ but I want it to redirect to http://127.0.0.1:8000/travello

echo summit
#

have you tried it with /travello ?

buoyant geode
#

no ill try

#

Thanks a lot it worked @echo summit

echo summit
#

👍

eternal blade
#

Any good free mailing service which I can use for my django web app?
I tried mailgun but it asks for company information

mild marsh
#

Use flask for python web development

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @mild marsh until <t:1631637932:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

torpid flower
#

scroll to where error is

#

aka red text

#

send screenshot

#

so it cant find the template

#

lets try to figure out why

#

is your html file named exactly index.html

#

and is in templates

#

its not in templates

#

templates is a folder

#

create that folder in your project dir and put the html file in there

#

it will be fixed

#

send screenshot of files again

#

yeah

#

would help

#

@native tide actually just send entire project folder

#

it could be the placement of files or the code itself

#

i need it all

lavish prismBOT
#

Hey @native tide!

It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.

Feel free to ask in #community-meta if you think this is a mistake.

torpid flower
#

bruh

#

dm it

glacial dock
#

Anyone know if it’s possible to build an iOS app with a Python/FastAPI backend? Haven’t been able to find any documentation on this particular implementation

dense slate
#

Just use a front-end framework like React Native

#

and fetch from an API built on whatever you want to use

dusk portal
#

Don't write templates/ inside render templates it identifies that itself bruh

silver swan
#

How many concurrent requests(requests per second) can a Nginx server handle with specifications 1vcpu and 2gb ram and using Ubuntu 16

I followed the following link to deploy my django website,

https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04

DigitalOcean

Django is a powerful web framework that can help you get your Python application or website off the ground. Django includes a simplified development server for testing your code locally, but for anything even slightly production related, a more secure

frosty elk
#

Which is best to use for django views, def example(request) or def example(response),?

#

Started learning django a few days ago

dusk portal
#

What r u saying lol

#

Response is like return but in rest Framework

#

;_;

#

And and yes in both the parameter is request

#

Example

def babe(request):
     return render(request,"babe.html")```
#
from rest_framework.response import Response
def babe(request):
    return Response("babe") 
#

Or JSONRESPONSE

#

We won't use html here as it is given my django

#

And Functionality

frosty elk
#

Noted, Thank you

dusk portal
#

Yes

#

Take ur time
First CleverProgrammer 8 hrs video on which he covers docs
U should take 1 week to do that if u code 6 hrs a day
Cez u urself have to code as he copy from docs + read the docs

#

Then Corey Schafer playlist

#

And remember
3 gods of django
JUSTDJANGO
CODINGFORENTERPRENEUR
DENNIS IVY

dusk portal
#

Kind of obsessed as I am too

frosty elk
#

and thank you will look at those definitely

dusk portal
dusk portal
#

Practice alot

frosty elk
#

Thank you again @dusk portal

dusk portal
#

Nah no need

#

Stay connected

#

Btw u know any other field rather then web d

cerulean laurel
dense slate
cerulean laurel
#

am i making a correct model for my usage now, i mean i m really beginner with django and used to go with the django auth and not making a model for the user

frosty elk
#

@dusk portal I dabbled a bit with game dev using Godot last year, but I feel web dev is best field to get into at the moment, did my basic overview of the different developer fields at college this year. But I find backend web dev very interesting, that's the path I would like to go, hence why I started learning django.

dense slate
#

Looks fine. There's a good page for creating your own user model...

#

Make sure you include your custom user model in your first migration.

cerulean laurel
#

thank you sir

#

sir please, so i am not forced to use from django.contrib.auth.models import AbstractBaseUser, BaseUserManager?

frosty elk
#

I'm looking to learn how to use bootstrap, and maybe pickup react afterwards, while trying to build projects on my own with django to learn it.

#

@dusk portal are you working in the backend or are you full stack?

dusk portal
#

Mainly Backend

#

Api

#

Nd the DevOps part too (learning)

frosty elk
mortal pike
#

Anybody know how to link a django site to a physical robot on the same network using either sockets or http or something else. If you could help that would be great

dense slate
#

What's the purpose? Send commands from the site to the robot?

wraith topaz
#

how can I move my img to the top right conner of my header

#

i tried this align="right"but it not working it only moves it a lit bit

mortal pike
vestal hound
#

I'm assuming the robot has a working client

#

or server?

#

anyway, one needs to initiate a connection to the other

mortal pike
vestal hound
#

django-channels?

mortal pike
#

I haven't used channels before, only socket

vestal hound
#

🥴

#

like

#

the Python stdlib socket library?

#

do the server and robot need to talk to each other?

#

or one way only?

mortal pike
#

For right now only the websit needs to talk to the robot

vestal hound
mortal pike
#

Maybe, but for now lets just go with tihs

vestal hound
#

you didn't answer my question

#

about socket

mortal pike
halcyon fox
#

I'm trying to pass data from my app.py in flask to a server-side application that has a googlemaps api

#

My issue is the data isn't being passed from flask to my serverside and results in a webpage error. But when I try to acesss the page from my flask application it returns the correct json data.

#

Here is the code for my app.yp

#
from flask_cors import CORS
from flask import Flask, jsonify
from processdata import processdata
app = Flask(__name__)
CORS(app)
@app.route('/displaylocations/')
def displaylocations():
    l = processdata()
    return jsonify(l)
if __name__ == '__main__':
    app.run(host = "127.0.0.1", port = 5002)


#

I basically copied this with a few adjustments for the rest:

lapis stratus
#

Hello, I'm getting a non field error in django but when I checked the request payload in the network tab the credentials are correct

lusty wigeon
#

Anyone who want to help me in django.. I have asked a quetion in pie chats..

west mulch
#

i am trying to deploy a django app to heroku

-----> Building on the Heroku-20 stack
-----> Determining which buildpack to use for this app
-----> Python app detected
-----> Using Python version specified in runtime.txt
 !     Requested runtime (python 3.8.12) is not available for this stack (heroku-20).
 !     Aborting.  More info: https://devcenter.heroku.com/articles/python-support
 !     Push rejected, failed to compile Python app.
 !     Push failed

but clearly

#

3.8.12 is a supported version

#

the app runs locally without any issue

stiff totem
#

So i am using django. and i have following model

class Collection(models.Model):
    title = models.CharField(max_length=10)

class Item(models.Model):
    collection = models.ForeignKey(Collection)
    object_id = models.UUIDField()
    seq = models.PositiveSmallIntegerField()

from the frontend Item can be drag&dropped to change its seq value. Hence i need to update the seq value. If seq value is duplicated, i have to add 1 to the previous one and place the new one instead. I am thinking collecting all the items and updating each one but is there any other optimal way to achieve this?

civic crater
#

Any good docs to learn django forms

cerulean badge
#

i have setup redis broker for celery and i want to use redis db for recommendations as well, is there a configuration i need to do to prevent conficts?

coarse shadow
#
from flask import Flask, request

App = Flask(__name__)

@App.route('/')
def HomePage():
    return '''
    <form method = "POST" action = "/create" enctype = "multipart/form-data>
        <input type = "text" name = "longurl">
        <input type = "sumbit">
    </form>
    '''

@App.route('/create', methods = ['POST'])
def Create():
    print(request.form.get('longurl'))
    return 'Done'

if __name__ == '__main__':
    App.run(host = '0.0.0.0', debug = True)```
its keep printing `None`, how i can get text from input form?
buoyant geode
#

Hi can some one help me to understand what is the use of reverse() in Django, I tried to understand but I'm unable to Thank you

sturdy vale
#

How can I setup HTTP server that just prints out every request info?

tiny snow
#

Run this in a folder with presumably static website files like index.html and whatever

sturdy vale
#

Does it print out requests?

#

Well I'm just gonna give it try

#

Damn it works

#

thanks a lot

mint palm
#

Ik this a dumb question but i dont understand how input labels work in html

mint palm
#

I don't get why they can be used without nesting in input element

vestal hound
#

you mean in conjunction with for?

#

like <label for...>

mint palm
#

Yep

vestal hound
#

honestly

#

that's just a HTML thing

#

I don't think there's any explanation other than historical accident

mint palm
#

Ohh, thanks

vestal hound
#

HTML has evolved a lot from a long time ago

#

at the same time, backwards compatibility is a thing

#

so I wouldn't worry so much about it

mint palm
#

Ah, I see

stable sentinel
#

in django I am storing some images for my portfolio projects in
model.FilePathField(path='/img') and this makes my admin panel crash with a FileNotFound exception cause of the /img dir.
Project photos do not load cause django is looking for them in /static/static/img instead of static/img.

If I change the path attribute to model.FilePathField(path='static/img') admin page works but I still get a 404 cause django is looking for files in static/static or static/home...

Someone please give me a hand cause this is the only thing holding me back from deploying my portfolio page. And its been bugging me for weeks by now...

#

I truly have no idea which constant in the settings.py is prefixing the path with static. I have played around with a multitude of things