Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Weather API not getting data from other locations
**I am creating a weather app in django and i want the users to be able to search for weather on any locations using the API...i have tried multiple times to use the HTML input but it's not working def home(request): choose_city = "London" #selected city url = f"https://openweathermap.org/data/2.5/weather?q= {choose_city}&units=imperial&appid=b6907d289e10d714a6e88b30761fae22" #open weather url response = requests.get(url) get_weather = response.json() for weather in get_weather["weather"]: pass temperature = get_weather["main"] city_name = get_weather["name"] weatherContext = { "main" : weather["main"], "description": weather["description"], "temp": temperature, "city_name": city_name, "city": choose_city, "url": url } return render(request, "MyWeather/base.html", weatherContext) here is the HTML Blockquote <div class="wrapper"> <div class="container"> <nav class="navbar navbar-light bg-light" id="nav"> <form class="form-inline" action={{url}}> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" > <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search </button> </form> </nav> <br> <div> <h2> City: {{city_name}} </h2> </div><br><br> <h4>Weather: {{main}}</h4><br><hr> <h4> Description: {{description}}</h4><br><hr> {% for temperature, key in temp.items%} {%if temperature == "temp"%} <h4>Temperature: {{key}} °F</h4><br><hr> {%endif%} {%endfor%} How can i be able to resolve this issue -
How to find the acme challenge response?
I'm using a django-letsencrypt and it requires me to enter in the acme challenge and the acme challenge response. I'm able to find the challenge but I'm not able to find the proper response to use. Where can I find the response? I'm using acme V2 -
Creating Django´s blog Post custom fields
I am new to django, I am trying to add custom fields to the regular django blog Post App. This is the blog fields out of the box: models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title I need to create 4 fields: Types (charfield length=200) Status of item (combobox with OK and NOK options) Ranking (numbers, 1-10) Deployed (charfield length=200) I have tried simply adding those fields to my models.py below but it breaks the website: title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) Types = models.CharField(max_length=200, unique=True) etc Error on my anaconda prompt: TabError: inconsistent use of tabs and spaces in indentation Where else do I need to add the fields? DO I need to create a separate class? If so, how do I add to the create post backend? -
How to Use Django File Storage to Share Files Between an API and a Worker
Goal I want to build a local docker compose deployment such that I have 5 services. Redis Postgres RabbitMQ Django API Django Worker In this deployment the user uploads a file via the API endpoint. This endpoint will store the file in a FileField field in a model. In a separate transaction the user will trigger an asynchronous task via a separate endpoint. This task will be responsible for downloading the file extracting the file kicking of sub tasks to perform intermediate processing steps upload the results of the processing to the database The intermediate processing steps are NOT supposed to upload any of the files to the database. The intermediate processing steps are to use django's internal file storage solution to download and upload files there. This is implemented with a file system hierarchy that is not relevant to this question. The Problem I have managed to get my local file system working with this configuration. If I run the backend of redis, postgres, and rabbitmq. And then, I run the API and Worker on my machine locally everything runs fine. When I create a docker-compose configuration and decouple everything. The operation seems to break. And in my docker-compose … -
MySQL startup ERROR! The server quit without updating PID file
I'm trying to start mysql in a Mac using sudo /usr/local/mysql/support-files/mysql.server start. I keep getting the following error - ERROR! The server quit without updating PID file (/usr/local/mysql/data/My-MacBook-Pro.local.pid). How do I solve this? I have tried uninstalling and reinstalling mysql using home-brew. I have also tried sudo chown _mysql /usr/local/var/mysql/* and other things mentioned in other answers. My-MacBook-Pro:~ myusername$ sudo /usr/local/mysql/support-files/mysql.server start Starting MySQL ... ERROR! The server quit without updating PID file (/usr/local/var/mysql/My-MacBook-Pro.local.pid). -
how do I add a friend system to my carpooling app
I am creating a website for carpooling as a class project. I need to implement a friend system on my website. It is just a simple friend system where users can add or remove another user as friend, no friend requests necessary. I would also need to display the list of friends for a user in the HTML template. I am very new to Django and web development. I am using AbstractUser from django.contrib.auth.models as my user model. from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass def __str__(self): return self.email class UserFriends(models.Model): current_user = models.ForeignKey(CustomUser, related_name='owner', null=True, on_delete=models.CASCADE) users = models.ManyToManyField(CustomUser, blank=True) def add_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create(current_user=current_user) friend.users.add(new_friend) def remove_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create(current_user=current_user) friend.users.remove(new_friend) def __str__(self): return str(self.current_user) -
Removing newlines from the end of base.html file makes some elements disappear from DOM
This is a strange bug. I have an html file that extends a base template called base.html. I noticed that a script tag right before the end body tag in the base template doesn't show up in the DOM in the Elements tab of the Chrome dev tools, and the tag is cut off completely along with the rest of the html file in the Sources tab. This happens in Chrome, Mozilla, and Safari, so it must be a problem on the Django side. And obviously the observable effects on the page that the script should create aren't happening either. Here's the end of that base template in the Sources tab: <section> what is going on </section> <footer></footer> <script src="/static/home/js/ba Completely cut off. Here's the end of that base template: {% block main %}{% endblock %} <footer></footer> <script src="{% static 'home/js/base.js' %}"></script> {% block js %}{% endblock %} </body> </html> Now, here's where it gets funny. The trouble is at the end of the file, so I just added some newlines to see if there's any difference in the DOM is rendered: {% block main %}{% endblock %} <footer></footer> <script src="{% static 'home/js/base.js' %}"></script> {% block js %}{% endblock %} … -
Django: how to have dynamic values in separate javascript files?
I would like to keep the javascript logic in separate files from the Django templates. However, some of the logic contains dynamic values which I would like to still be rendered just like templates. For example, ajax calls will contain urls url: "{% url 'app:list' %}", When the script is directly in the template, this is replaced by the proper url. When the code is in a separate .js file and is included this way: <script type="text/javascript" src="{% static 'js/list.js' %}"></script> The url is not replaced and the code appears just as it is. How to solve this? Thank you -
Howto configure Gmail account / Django Mailbox to receive incoming mails
I want to process email from a gmail account via Django. I installed latest django-mailbox. I created a gmail account, and created a Mailbox in django admin: imap+ssl://EMAILADDRESS%40gmail.com:PASSWORD@imap.gmail.com according to the manual. But django mailbox doesn't receive any mails. I think I have to tell gmail to allow django to access the mails. Any hints are appreciated, thanx in advance, Jan -
Can't get Django's get_absolute_url to set up the link properly
I am trying to use the get_absolute_url function in one of my templates like so: template.html <div class="card-columns"> {% for category in main_categories %} <div onclick="document.location = {{ category.get_absolute_url }};" class="card"> I'm fairly new to programming in general so I'm not sure if that is the correct way to do it, but I have been able to get it to return a couple views individually by using if statements like this: models.py def get_absolute_url(self): if self.pk == 1: return reverse('forum:index') if self.pk == 2: return reverse('tutorials:cybertips') return reverse('tutorials:subjects', args=[str(self.pk)]) I don't get any errors, and when clicking on the cards with pk=1 & pk=2 it returns the correct url pattern. The other cards loads fine but don't link to anything. When inspecting the html it looks like it returns a url so I'm wondering if i'm not understanding the onclick function? Here are my urls(in this app): urls.py app_name = 'tutorials' url_patterns = [ path('category/<int:pk>/', views.SubjectView.as_view(), name='subjects'), path('cybertips/', views.cybertips, name='cybertips'), ] views.py class MainCategoriesView(ListView): model = MainCategory context_object_name = 'main_categories' class SubjectView(ListView): model = Subject context_object_name = 'subjects' Any help is appreciated. Or if there is a more efficient and safe way to do it. Thank you. -
Filter json records in Django Rest Framework
I created a DRF API endpoint in order to be able to grab some data to my database and show it on my Django page using Jquery. My sample data looks like this: { "item": "Someitem", "Price": 120, "Status": "Free" }, { "item": "SecondItem, "Price": 90, "Status": "Taken" }, So if i retrieve the endpoint from JQuery to this link: http://127.0.0.1:8000/tst/, i'll get all the records and have all of them shown in my web page. But what if, for example, i only want to retrieve only the records whose Status field is set to Taken? Is there any way to edit the DRF request so that it points to http://127.0.0.1:8000/tst/Taken? Yes, i can do it with Jquery, but i would rather do it from Django instead. I'm fairly new to DRF, so my setup is pretty basic: views.py class tstList(generics.ListCreateAPIView): queryset = tst.objects.all() serializer_class = tstSerializer class tstDetail(generics.RetrieveUpdateDestroyAPIView): queryset = tst.objects.all() serializer_class = tstSerializer url.py path('tst/', views.tstList.as_view()), path('tst/<int:pk>/', views.tstDetail.as_view()), models.py class tst(models.Model): item = models.CharField() Price = models.FloatField() Status = models.CharField() def save(self, *args, using=None, **kwargs): super(tst, self).save(*args, **kwargs) -
Bootstrap 4 Multifield Equivalent
Django Crispy Forms has a multifield layout for the uni-form template pack - https://django-crispy-forms.readthedocs.io/en/latest/layouts.html#uni-form-layout-objects. Errors in the form are shown in a list at the top of the form. Whereas normally errors are shown beneath the field they concern. It doesn't seem such an option is supported in bootstrap4 (having read the docs for the first time) so I wondered if anybody knew a way of achieving this easily? -
I don't know why Nginx server is not working
Hi there i'm trying to put in production some django app using nginx + gunicorn + supervisor. Following this guide i was able to reproduce all steps with success but for some reason i can't make it work. I believe that the problem is with the nginx part of the project since i'm not able to even serve a static file for testing. It's my first time using all these tools. Config files are as follows: nginx.conf: worker_processes 1; user nobody nogroup; # 'user nobody nobody;' for systems with 'nobody' as a group instead error_log /home/seba94/log/nginx/nginx.error.log warn; #pid /run/nginx.pid; events { worker_connections 1024; # increase if you have lots of clients accept_mutex off; # set to 'on' if nginx worker_processes > 1 # 'use epoll;' to enable for Linux 2.6+ # 'use kqueue;' to enable for FreeBSD, OSX } http { include /etc/nginx/mime.types; # fallback in case we can't determine a type default_type application/octet-stream; access_log /home/seba94/log/nginx/nginx.access.log combined; sendfile on; upstream app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response # for UNIX domain socket setups server unix:/tmp/gunicorn.sock fail_timeout=10s; # for a TCP configuration #server 127.0.0.1:8000 fail_timeout=0; } server … -
I am having issues uploading a Python project (using Django) to Heroku
I am trying to deploy a Python project to Heroku. When i press the "Deploy Branch" button on the Heroku website ... https://dashboard.heroku.com/apps//deploy/github i get this error. Installing requirements with pip $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog' Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets Push rejected, failed to compile … -
check if string matches first n characters of regex
I have a python site built in Django where a user will be uploading files that they may or may not have permission to add. The permissions are created through a series of regex patterns (there is over 1000). At one point in my site I have a place for the user to view their permissions (using a search filter and a list). However what I want to do is if the user types in a string and the string matches any part of each regular expression. I want it in the list. Right now I have if(filter.match(pattern)) { //add pattern to list } I have also tried searching instead of matching. An example of what I am looking for: If I have a list of regex patterns: ^(12345678)\.(txt)$ ^(qwertyuiop)\.(txt)$ ^(qwerty)\.(txt)$ ^(23456)\.(txt)$ if the user were to enter qwert the list would show ^(qwertyuiop)\.(txt)$ and ^(qwerty)\.(txt)$, whereas if the user entered qwertyu the list would only show ^(qwertyuiop)\.(txt)$. Similarly if the user entered 234 the list would show ^(12345678)\.(txt)$ and ^(23456)\.(txt)$ but if the user entered 1 the list would only show ^(12345678)\.(txt)$. Is it possible to accomplish this? If so how would I manage it? Thanks for the Help! -
Vue.js - Flask vs Django
I am a total newb to node/js/vue/react/yadda yadda. I am trying to follow blogs on setting up Vue with Flask (i want pretty flask sites!) but they are all inconsistent and confusing. I have Flask experience so i would love to use Flask backend but I am getting very discouraged that I've been working for 6 hours and have yet to even have a basic site setup. Is it worth it to try Django? Should I ditch python all together? I am frustrated, I dont have anywhere else to ask for advice so I am turning to SO. Thanks so much. There should be a "DESPERATION" tag for folks like me posting to SO in desperation :). -
Django Rest Framework tests fail and pass, depending on number of functions
I have a test class in Django Rest Framework which contains a function which passes the test if it is the only function in the class, or fails if it is one of two or more functions. If I run the below code as is, i.e. def test_audio_list(self) function remains commented out, the test passes as per the two assert statements. If I uncomment def test_audio_list(self) function and run the tests, the def test_audio_retrieve(self) function will fail with a 404 whilst def test_audio_list(self) will pass. Here is my full test case (with def test_audio_list(self): commented out). class AudioTests(APITestCase): # setup a test user and a factory # factory = APIRequestFactory() test_user = None def setUp(self): importer() self.test_user = User(username='jim', password='monkey123', email='jim@jim.com') self.test_user.save() # def test_audio_list(self): # """ # Check that audo returns a 200 OK # """ # factory = APIRequestFactory() # view = AudioViewSet.as_view(actions={'get': 'list'}) # # # Make an authenticated request to the view... # request = factory.get('/api/v1/audio/') # force_authenticate(request, user=self.test_user) # response = view(request, pk="1") # # self.assertContains(response, 'audio/c1ha') # self.assertEqual(response.status_code, status.HTTP_200_OK) def test_audio_retrieve(self): """ Check that audo returns a 200 OK """ factory = APIRequestFactory() view = AudioViewSet.as_view(actions={'get': 'retrieve'}) # Make an authenticated request to the … -
how i do post request with python-requests-library, if in my model i have images field
i need a help, i creating telegram bot , bot get to api post request, and in my model i have images field, when i do post request, i got a fail "bad request" 400, how i can fix this problem? requests.post(url='http://127.0.0.1:9999/api/create/',data={ 'title':message_title.get(message.chat.id),'images': message_photo.get(message.chat.id), 'lot': message.location.latitude, 'lang': message.location.longitude, }) "POST /api/create/ HTTP/1.1" 400 103 it's error -
Django function view to update two templates (current and base)
Django Beginner. I have a functioning Django app (models, views, urls, templates) similar to what you can see in tutorials. I would like to return some debugging and user information (e.g. if an item already exists in a table) into a terminal-like section in my base.html. Inside my standard view function call (turning an uploaded csv file to pandas and generating inserts into my normalized tables) I added a 2nd render(request,...) that sends a dictionary to my base.html. def bulkinsert(request): data=None context=None if request.method== "POST" and request.FILES['myfile']: myfile = request.FILES['myfile'] df=pd.read_csv(myfile ) data_html=df.to_html() context={'data': data_html } m='' # now read each row and insert lot, sublot, ... for index, row in df.iterrows(): if pd.notna(row['lot']): lotname=row['lot'] ... # check existence of this lot f1=Lot.objects.filter(lotname=lotname).count() if f1==0: m+='\n Lot did not exist yet, inserting ...' b1=Lot(lotname=lotname) b1.save() else: m+=f'\n Lot {lotname} already exists' ... c2={ 'memo': m} render(request, 'lenses/base.html',c2) return render(request, 'bulkinsert.html',context) else: form=UploadFileForm() data=None context=None return render(request, 'bulkinsert.html',context) What do I have to add to my base.html to pass that dictionary (c2) into the desired html-section? So far I have just: {% block c2 %} <p>{{ memo }}</p> {% endblock %} but the page does not update as I expected. -
Why use UniqueTogetherValidator over Django's default validation behavior?
I have a Django model defined with a unique_together relationship defined between name and address, shown below: class Person(models.Model): name = models.CharField(max_length=255, default='', null=False) address = models.CharField(max_length=255, default='', null=False) class Meta: unique_together = ('name', 'address') I also have a Django REST Framework serializer with a UniqueTogetherValidator describing the same constraint as defined in the model, shown below: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ( 'name', 'address', ) validators = [ UniqueTogetherValidator( queryset=Branch.objects.all(), fields=['name', 'address'] ) ] While testing this constraint, I noticed that the exact same behavior is exhibited whether or not I have the UniqueTogetherValidator added to the PersonSerializer. The same error message is returned whether or not I include this (due to the unique_together defined on the model). My question is: what is the reason for explicitly declaring validators on the serializer if the behavior is performed behind the scenes? I did notice you can change the error message, but this seems like quite a bit of boilerplate for solely manipulating an error message for violating a unique_together constraint. Is there a broader reason for utilizing these validator classes that I'm missing? -
error: "int() argument must be a string, a bytes-like object or a number, not 'list'" in decorator @action
Good afternoon I am doing an @action decorator to a viewset in django rest to filter my model by a field and some values in an list and thus obtain (properties) values that will be consumed in the api rest. My code is as follows: class EquiposViewSet(viewsets.ModelViewSet): queryset=Equipo.objects.all() serializer_class=EquipoSerializer @action(methods=['get'], detail=False, url_path='equipos-alarm', url_name='equipos_alarm') def equipos_alarm(self, request): # pylint: disable=invalid-name queryset=Equipo.objects.filter(id_equipo=[106,107,156,157]) return Response ( { 'id_equipo':equipo.id_equipo, 'nombre_equipo':equipo.nombre, 'hora_ospf':equipo.recorrido_ospf, 'hora_speed':equipo.recorrido_speed, } for equipo in queryset ) and the error that returns me is the following: int() argument must be a string, a bytes-like object or a number, not 'list' How can i fix this? -
Getting Object based on its ID
Setup I am trying to write a DeleteView that will delete an object based on its Id. The object is a journal and I want to reference the Journal that the user is currently located in. So for example if User1 is in Journal "Work" I want to delete that specific one based on journal Id and not anything else. My understanding is that Django creates an ID fields (Autofield) for each model. Error This is my current view: class DeleteJournal(LoginRequiredMixin, DeleteView): model = Journal tempalte_name = 'delete_journal.html' success_url = reverse_lazy('home') def get_object(self, queryset=None): id = self.kwargs['id'] return self.get_queryset().filter(id=id).get() The error I receive is this: What is the solution to this and why is it not working? Thanks a ton in advance, really appreciate anyone looking at this. -
Adding file upload widget for BinaryField to Django Admin
We need to store a few smallish files to the database (yes, I'm well aware of the counterarguments, but setting up e.g. FileField to work in several environments seems very tedious for a couple of files, and having files on the database will also solve backup requirements). However, I was surprised to find out that even though BinaryField can be set editable, Django Admin does not create a file upload widget for it. The only functionality we need for the BinaryField is the possibility to upload a file and replace the existing file. Other than that, the Django Admin fulfills all our requirements. How can we do this modification to Django Admin? -
List or table with field names as a column other than header
I am wondering whether it is do-able to make a list or table or any other solutions like:          Time 1    Time 2 FieldName1   a_Value1   b_Value1 FieldName2   a_Value2   b_Value2 FieldName3   a_Value3   b_Value3 The reason I want this is that I have 30+ fields, which will be ugly and not user-friendly if using an ordinary table. The structure of this is like 30 rows by 3 columns. -
how to add two fields as foreign key to a table?
I have two tables "team" and "match". every team can be on different matches and every match contain two or more teams and so it's a manytomany relation. here is my match model: class Match(models.Model): result = models.CharField(max_length=10, default='') winner = models.?????? team = models.ManyToManyField(Team, related_name='team') referee = models.ForeignKey(User, on_delete=models.PROTECT, related_name='referee') the winner of every match is also a team but I don't know how to handle it. should I define it as foreign-key to team table? what is the right way?