Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why my app is not loading in browser in GKE
I have my deployment script running with no errors. I have the service running with no errors. But when I load the external IP in the browser, it loads forever with the message: Here is my docker file: # pull official base image FROM python:3.8 EXPOSE 8080 # Install GDAL dependencies #RUN apt-get update && apt-get install --yes libgdal-dev #apt-get install binutils libproj-dev gdal-bin RUN apt-get update && apt-get install --reinstall -y \ binutils \ libproj-dev \ libmemcached11 \ libmemcachedutil2 \ libmemcached-dev \ libz-dev # Copy the application's requirements.txt and run pip to install all # dependencies into the virtualenv. ADD requirements.txt /app/requirements.txt RUN pip install -r /app/requirements.txt # Add the application source code. ADD . . CMD exec gunicorn --bind :8080 --workers 1 --threads 8 main:app --timeout 0 --preload Here is my deployment script: # [START kubernetes_deployment] apiVersion: apps/v1 kind: Deployment metadata: name: web labels: app: web spec: replicas: 3 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: web-app # Replace with your project ID or use `make template` image: gcr.io/app-kor/app-kubernetes:v0.0.1 # This setting makes nodes pull the docker image every time before # starting the pod. This is useful when debugging, but should … -
Dynamically find model objects in Django and update page with its data
I am stuck with a thing that I want to implement on my Django website. I want to have several inputs on a page where the user can select IDs of the objects from the database, and after they click on a button, the info about those objects need to be shown on the same page underneath. How do I do that properly with Django views and Model objects? Can I have multiple views or nested views in Django on a webpage? It wouldn't be much of an issue to send this data to a new page with another view, however, this has to be on the same page. Can anybody show me on a code example how this has to be done? -
Django sites framework with REST API
I have an existing Django project which uses the sites framework to produce data for several websites from the same database. At the moment, it renders the templates using Django templates but I'd like to create a REST API (using django-rest-framework) so that I can create the frontends using another framework, like vue. Before I go down that road, I want to get my head around how I can do this using the sites framework. Is it safe to assume that it's as simple as making sure that the frontend puts the site's domain in the HTTP request and Django will pick it up from there and return the correct data from the database? Or should I be thinking along different lines? -
"This field is required" keeps showing even all the input field is filled
Please help. The signup page keeps showing this field is required error. I'm a beginner. thankyouu models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, username, full_name, password=None): if not email: raise ValueError("Users must have an email adress") if not username: raise ValueError("Users must have a username") if not password: raise ValueError("Users must have a password") if not full_name: raise ValueError("Users must have a name") user = self.model( email=self.normalize_email(email), # return lowercase username=username, full_name=full_name, ) user.set_password(password) # users set password and change password user.full_name = full_name user.save(using=self._db)# using the default database in settings.py return user def create_superuser(self, email, username, full_name, password=None): user = self.create_user( email=self.normalize_email(email), # return lowercase username=username, full_name=full_name, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) # using the default database in settings.py return user class Account(AbstractBaseUser): email = models.EmailField( verbose_name="email", max_length=60, unique=True, ) username = models.CharField(max_length=30, unique=True) full_name = models.CharField(max_length=30, blank=True, null=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) profile_image = models.ImageField(max_length=255, null=True, blank=True, default=default_profile) hide_email = models.BooleanField(default=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "full_name"] objects = UserManager() # tie account to … -
Is transaction.on_commit executed as part of transaction?
If there is exception in the callback provided to on_commit does this rollback transaction or not? -
python django long polling waiting
I use Django with Rest Framework. I made a long polling view to return the latest update to other clients. To wait for long polling, I used time.sleep(seconds) function. but this seems it works only for the client who made change. other clients seems stuck in somewhere. Could you advice the right way to wait for long polling in Python Django ? class ChangedItemsPollingView(APIView): permission_classes = [permissions.IsAdminUser] def get(self, request): request_received_time = datetime.datetime.now() ten_seconds_later = request_received_time + datetime.timedelta(seconds=10) while(datetime.datetime.now() < ten_seconds_later): changed_items = Asset.objects.filter(updated_at__gt=request_received_time) if(changed_items): tmpJson = djangoSerializers.serialize('json', changed_items) tmpObj = json.loads(tmpJson) return Response(tmpObj) time.sleep(3) return Response([]) -
py manage.py startapp polls sous eclipse/django
J'ai créer une application avec la commande'' py manage.py startapp polls '' le fichier polls est créer.mais il ne figure pas sur ''ouvrir fichier'' d' eclipse/django ; comment le récupérer. -
Return redirect in returning NoneType instead of REDIRECTING - Python Django [ERROR]
Here I wan't to redirect the if sessions don't exist. But the function authenticate is returning None instead of rediecting to homepage. WHat's the solution... inside authenticate function: def authenticate(request): username = request.session.get('username') password = request.session.get('password') email = request.session.get('email') if username and password: user_data = User.objects.get(username=username, password=password) if user_data.is_active: return {'bool':True, 'ud':user_data} elif not user_data.is_active and username: redirect(f'verify/{username}') else: return False else: request.session.delete() return redirect('/') inside views.py def profile(request, username): auth = authenticate(request) -
Django: How to only display content made by a user to that same user?
I'm learning Django (obviously) and one thing I just noticed about a project I'm building is that initially, Each user could see objects/content made by every other user. For instance, my project is a very basic fantasy football app, I've set it up so that a user can create a team by adding listed players to my team model called "MyTeam" as seen here. class Myteam(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) QB = models.CharField(max_length=80, null=True) QBscore = models.IntegerField(null=True) RB1 = models.CharField(max_length=80, null=True) RB1score = models.IntegerField(null=True) RB2 = models.CharField(max_length=80, null=True) RB2score = models.IntegerField(null=True) WR = models.CharField(max_length=80, null=True) WR1score = models.IntegerField(null=True) WR2 = models.CharField(max_length=80, null=True) WR2score = models.IntegerField(null=True) TE = models.CharField(max_length=80, null=True) TEscore = models.IntegerField(null=True) D = models.CharField(max_length=80, null=True) Dscore = models.IntegerField(null=True) K = models.CharField(max_length=80, null=True) Kscore = models.IntegerField(null=True) I've learned about ForeignKeys for linking specific content to a particular user and the next step I'm trying to figure out is how to get it so that a logged-in user can only see their team and no one else's. I've been searching around here and other places via google, but as a Django noob, it's hard to even verbalize the right question to search for in the first place. I thought I … -
Python : Regex to parse 1w 5d 3h 6m?
I am able to parse days, hours and minute using the following regex, ^(\d+d)?\s*((?:[01]?\d|2[0-3])h)?\s*((?:[0-5]?\d)m) What I needed to support the week too (1w 5d 3h 6m)? -
Django strange behaviour in filter query with distinct
email_manager_obj = EmailManager.objects.filter(<some filter>) batchsize = 10 for count in range(0, email_manager_obj.count(), batchsize): batch = email_manager_obj[count:count + batchsize] for item in batch: item.is_email_sent = True item.number_of_email_sent += 1 EmailManager.objects.bulk_update(batch, ['is_email_sent', 'number_of_email_sent']) time.sleep(1) return True my question is: In email_manager_obj query when i running this program, column = my 'number_of_email_sent' has generating random counting and saves in DB. it supposed to count existing number +1, i dont know why is this happening, is this a bug or i am doing it wrong. Also i have tried with single query (item.save()) to updated individually. still happening same thing. After some time, i found when i use 'email_manager_obj' with distinct("id") email_manager_obj = EmailManager.objects.filter(<some filter>).distinct("id") then it is counting correct integer. (email_manager_obj contains no duplicate items from filter querset ) Strange behaiviour can someone suggest me if its a some kind of bug or my code issue. i am using Django 2.2.10, python 3.6, postgres -
Heroku sessions persist across browsers
I've run into a problem that I simply don't understand. I'm using Django with Heroku and everything works fine when running on localhost. But on Heroku sessions behave unexpectedly. First of all - why is my session synched on the server and not in individual browsers? When I input data from Chrome, I have the same data appear in Edge and in Anonymous new browser windows. I don't want this behaviour. I tried to change the backend session engine to file, cached_db and db, but everything behaves the same. It causes a lot of problems. Data are not transferred properly and I don't know what the problem is. I need to transfer data between two HTML templates. I'm sending the data forward as a dictionary: send_input = { 'artists': context['chosen_artists'], 'songs': input_songs, 'ids': input_ids, } request.session['send_input'] = send_input But something is off and I have no idea what is wrong. You can see it on http://das-music.herokuapp.com/model/checklist/ When you enter an artist, you can choose a song from that artist. Data are then stored in context dictionary because I'm reloading the page. You can choose a different artist and new songs. That's when the first problem happens. Data are not "saved" … -
django-allauth verification email send with example.com:port
I am working with django-allauth. I manage to do everything, however the port is rendered within confirmation email: so it looks like that: http://example.com:8000/accounts/confirm-email/NA:1kcaUA:3NeRmjX502XujDEy_PmwHsV_rW3ioNjOvWcclXFBD5 is there any way to get rid of the port while sending those ? Thanks in advance. -
Drango template not loading Facebook iFrame in Firefox
I am trying to load a Facebook Newsfeed iFrame into a Django template using <iframe src="https://www.facebook.com/plugins/page.php?href={{ obj.facebook_address }}&tabs=timeline&width=500&height=750&small_header=true&adapt_container_width=true&hide_cover=true&show_facepile=true&appId=myappid" width="500" height="750" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allow="encrypted-media"></iframe> This works when browsed with Chrome, but not Firefox or Edge. With Firefox and Edge I get a Facebook error message Your request couldn't be processed There was a problem with this request ... If I take the src from the iFrame (ie https://www.facebook.com/plugins/page.php?href={{ obj.facebook_address }} and post that as the url then I get the iFrame loaded into my Firefox browser so I think it is something to do with my site causing the issue (presumably the headers), but I cannot work out what it is. Of course, thinking it the headers could be a red herring. I can get the feed to show if I disable Enhanced Tracking Protection in Firefox, but I cannot believe other sites simply allowing this to slide so I think there must be a solution which doesn't depend on the user amending the settings I've spent 5 hours trying to work out the issue and I have got nowhere. Any help much appreciated -
Why does django-haystack run the object preparation multiple times?
I'm having this in my SearchIndex: class UserIndex(SearchIndex, Indexable): text = CharField(document=True, use_template=True) likes = IntegerField() def index_queryset(self, using=None): return self.get_model().objects.all() def get_model(self): return User def prepare_likes(self, obj): # Logging here just because it's the first "prepare" function. log.debug("Indexing %s: %d" % (obj.__class__.__name__, obj.pk)) return obj.get_all_likes() I have one object in my database. When I run update_index, the log.debug is printed 3 times for the object with pk 1. What am I doing wrong? -
Angular10 File Upload to django Server
I'm trying to upload a CSV file using Angular HTTP Client. But when i check the request.FILES in backend it shows <MultiValueDict: {}>. Apparently the file data is coming in request.body as byte string. Below is sample angular code for you reference. const upload_url = `${BASE_URL}/data-upload`; // Create form data instance const formData: FormData = new FormData(); formData.append('data_file', file, file.name); // Update header const headers = {'Content-Type': 'multipart/form-data'} this.http.post(upload_url, formData, {headers: headers}).subscribe(res => { console.log(res); }); How can i get the same file data in request.FILES? -
Django caching simple auth token
I have an app which uses Django DRF with simple AuthToken, Postgres for database and Redis for caching. I am trying to reduce the number of calls to my DB and one of most common action is SELECT on AuthToken table. In fact, it needs to be called for every request on a protected endpoint to verify the permission of the user. We could reduce the number of calls to our DB by caching the token of users in Redis as {user_id: token}. Assuming we set a decent expiration for the key and that we invalidate it in case of revoked token AuthToken, is caching the auth token an anti-pattern? Is there any security issue I should be concerned about? -
Django Admin. Giving permission to a user or a group and on save, I have 500 server error
If I try to assign the user to a group or assign permission to a group or a user, I have 500 server error fault. I have the following models.py, it's in: /home/e/sc_project/sc It's autogenerated, it tells me the following message for every table in the database: This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models # Unable to inspect table 'auth_group' # The error was: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ # Unable to inspect table 'auth_group_permissions' # The error was: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ and so on... That's because I have 9.2 PostgreSQL database(?)... Can it give me … -
Add additional keyword argument when overriding __init__ for Form
I want to create a form and overriding the __init___ as following: class ModifierForm(forms.Form): dummy = forms.BooleanField(required=False, widget=forms.HiddenInput()) def __init__(self, modifiers, *args, **kwargs): super().__init__(*args, **kwargs) if len(modifiers) > 0: if 'applies' in kwargs: applies = kwargs.get("applies") for modifier, applied in zip(modifiers, applies): self.fields[modifier] = forms.BooleanField(required=False, default=applied) else: for modifier in modifiers: self.fields[modifier] = forms.BooleanField(required=False) Here, I pass a mandatory list modifiers. I also want to pass an optional list applies so as to set the initial default values to the fields. But when I call this form as below, I get this error __init__() got an unexpected keyword argument 'applies' modifier_change_form = ModifierForm(modifiers=modifiers, applies='applies') But it works fine if I just call as following, without applies: modifier_change_form = ModifierForm(modifiers=modifiers) I suspect that the **kwargs is from the base Form class only. How do I insert additional but optional **kwarg argument in __init__? Thanks. -
Map User and Board in Django
I'm trying to build Reddit in Django and for that, I am creating a board where users can discuss topics. But I am not able to map user and board. Model: class Board(models.Model): id = models.AutoField(primary_key=True) unique_id = models.CharField(max_length=100, null=False, unique=True) created_by = models.ForeignKey(User_Detail, on_delete=models.CASCADE, related_name="board_creator") name = models.CharField(max_length=100, null=False, unique= True) class UserBoardMapping(models.Model): user = models.ManyToManyField(User_Detail) board = models.ManyToManyField(Board) user_type = models.CharField(max_length=10, choices=USER_TYPE, default='moderator') My view: class CreateBoard(APIView): def post(self, request): data = JSONParser().parse(request) unique_id = data.get('board_id', None) created_by = data.get('created_by', None) name = data.get('name', None) if not created_by or not name: return Response({'ERROR': 'Please provide both username and password'}, status=status.HTTP_400_BAD_REQUEST) if Board.objects.filter(name=name).exists(): return JsonResponse({'ERROR': "Board Already registered! "}, status=status.HTTP_409_CONFLICT) if not User_Detail.objects.filter(username=created_by).exists(): return JsonResponse({'ERROR': "Username is not registered! "}, status=status.HTTP_404_NOT_FOUND) username = User_Detail.objects.get(username=created_by) board = Board(unique_id=unique_id, created_by=username, name=name) board.save() user_board_mapping = UserBoardMapping(user=username, board=board) user_board_mapping.save() UserBoardMapping is not working, how can I map user and board. what am I doing wrong here in this code ? -
Is running makemessages necessary every time?
I'm reading the django documentation for makemessages but the wording is not very clear: Runs over the entire source tree of the current directory and pulls out all strings marked for translation. It creates (or updates) a message file in the conf/locale (in the Django tree) or locale (for project and application) directory. After making changes to the messages files you need to compile them with compilemessages for use with the builtin gettext support. In the text above it doesn't seem clear to me what it means that makemessages would "pull out" strings marked for translation. (pull them out for what? where to?) Meanwhile the compilemessages description makes sense as this simply compiles the messages once I've changed the language files. When, if ever, should I use makemessages if compilemessages does the job I am seeking? What is the point of makemessages? -
how can i display the properties of my models that are stored in the QuerySet object?
My django app has a simple model, i created 3 instances, each has title and description properties, how can i use these properties to display in html template? models.py: from django.db import models class Solution(models.Model): title = models.CharField(max_length=200, help_text='Enter a title of solution') description = models.TextField(max_length=1000, help_text='Enter a description of solution',) def __str__(self): return self.title views.py: from django.shortcuts import render from .models import Solution from django.views import generic def index(request): solutions = Solution.objects.all() return render(request, "main/index.html", {'solutions': solutions}) I need to do something like this in a file html: <div class="content"> <h3>{{ solution.title }}</h3> -
Django: Format raw HTML to actual HTML (RichText)
I'm using Django to build a site and one of my models has a RichTextField (using ckeditor) So in my HTML template I use: {{ mymodel.richtextcontent }} But then my page displays the rich text field's tags like <p> or <em> for example. How do I make it considered normal HTML ? -
How to create a new object in Saleor Commerce?
Could somebody guide me how to add a new object to the projects? For example, Banner. Dashboard should be able to create, edit, delete banners. The banners will then be display on the storefront. I'm new to Python/Django. I watch a tutorial and find out that I may need to create an app so I do: python manage.py startapp banner but it always show the error: No module named 'module names' . After I install one it shows another. I've already run docker-compose build before, and I think it should already install everything. Thanks for your support :) -
If statement in Django not displaying the output
I want to display a delete button alongside comments that the request.user has written so that only they can remove them, but for some reason can't get my if statement to work. Here is my template: {% for post in posts %} ... {% if post.comment_set.all %} {% for comment in post.comment_set.all %} <img src="{{ comment.user.image }}"> <p>{{ comment.body }}</p> {% if comment.user == request.user %} # delete icon with modal {% endif %} {% endfor %} {% endif %} {% endfor %} It is the if comment.user == request.user tag which is not working. I have tried outputting both comment.user and request.user in <p> tags and both display the way I would expect, so can't understand why it doesn't work. I have also tested the delete button which does display correctly when the if statement is removed. Here are my relevant models for reference: class Comment(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField() class Post(models.Model): content = models.TextField() author = models.ForeignKey(Profile, on_delete=models.CASCADE) image= models.ImageField(blank=True, null=True, default='profile_pics/default.png', upload_to='profile_pics') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Strangely, further up the page I have used similar code to display delete beside the blog posts themselves, using {% if post.author.user …