Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - create new Objects when new user is registered
I am working on a bet app / guessing app. The user can bet on all NFL games and guess the correct result. So I made 4 Models (2 relevant for my current problem): class Customer(models.Model): name = models.ForeignKey(User,on_delete=models.CASCADE) points = models.IntegerField(null=True, default=0) class Tipp(models.Model): # model for one gameday (17 gamedays at all) user = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) week = models.ForeignKey(Game, on_delete=models.CASCADE, null=True, blank=True) result_hometeam1 = models.IntegerField(null=True, blank=True) result_guestteam1 = models.IntegerField(null=True, blank=True) ... So there are 16 games every week the user can bet. For this I created a form and implement in the template: class Tipp_form(ModelForm): class Meta: model = Tipp fields = '__all__' # views.py def week(request, pk): game = Tipp.objects.get(id=pk) form = Tipp_form(initial={'user':request.user, 'week':game}, instance=game) if request.method == 'POST': form = Tipp_form(request.POST, instance=game) if form.is_valid(): form.save() return render(request, 'main/week.html', { 'game': game, 'form': form, }) everything is working perfectly but now if a new user register I dont want to create 17 new weeks with 16 games every gameday! Is there a way to say: if a new user is logged in, create 17 new objects in Tipp and set user = new User? -
django filters.py @property def qs user
I am trying to filter the associated_portfolios fields object to only those created by the user. Which worked before I tried to add pagination (which is working if I remove the current filter I have for associated_portfolios) I believe what I need to do is remove: def associated_portfolios this is because it seems request is not past with the new setup. Instead, I should use this method https://django-filter.readthedocs.io/en/stable/guide/usage.html#filtering-the-primary-qs filters.py current; not working after adding pagination def associated_portfolios(request): associated_portfolios = Portfolio.objects.filter(user=request.user) return associated_portfolios.all() class TradeFilter(django_filters.FilterSet): associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios) date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry', widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = Trade fields = ['status', 'type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] filters.py possible solution based on documentation class TradeFilter(django_filters.FilterSet): date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry', widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = Trade fields = ['status', 'type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] @property def qs(self): parent = super().qs user = getattr(self.request, 'user', None) return parent.filter(user=user) The problem is the is no error message but the objects not created by the user are still showing. Tried probably a dozen + variations of this @property from what I've seen on SOF and the docs but no success yet.. views.py class FilteredListView(ListView): filterset_class = None def get_queryset(self): # … -
MultiValueDictKeyError at /search/
views.py def search(request): query=request.GET['origin'] if request.method=='GET': if query is not None: flightsearch=flight.objects.filter(origin_icontains=query) return redirect('searchresult/') return render(request,'search.html') // search.html {% csrf_token %} <div class="row"> Origin: <div class="col"> <div class="input-field col s10 m6"> <select style="display: inline; width: 250px; height: 30px;" name="origin" > <option value="" disabled selected>Choose Source</option> {% for ori in flight %} <option value="{{ori.id}}">{{ori.origin}}</option> </select> </div> </div> </div> -
Django query is very slow - filter and order by DATE, multiple additional filters
In my Django app, a UserProfile subscribes to many Artists (M2M) through a Subscription table (OneToOne with each). An Artist has an M2M relationship with Releases. I'm trying to display the relevant releases to to users, these should be: released within the last month (release date range: [month_ago, now]) from an artist the user follows have a type field that is in the user's wanted_type They should be distinct, and ordered by their release date. I have an index on Release.release_date (notice: DateField, not DateTimeField). This query is taking quite a long time. Often more than 10 seconds. Here's how I'm doing it: # notice: some model names are actually different in the database, they do match in actual code # selectors.py def get_releases_for_profile(profile: UserProfile): profile_wanted_types = profile.get_release_types() profile_art_ids = profile.subscription_set.all().values_list("artist__id") releases = Release.objects.filter( artist__id__in=profile_art_ids, type__in=profile_wanted_types ) return releases # views.py day_offset = 30 delta = timedelta(days=day_offset) past_delta = now - delta profile_rgs = selectors.get_releases_for_profile(profile=current_profile) past_month_releases = ( profile_rgs.filter(release_date__range=[past_delta, now]) .order_by("-release_date") .distinct() .prefetch_related("artist_set") ) context["past_month_releases_count"] = past_month_releases.count() context["past_month_releases"] = past_month_releases[:20] If I dump PostgreSQL's cache with sync && sudo purge to avoid calling it from the cache, this takes anywhere from 10-14 seconds. Debug toolbar is showing me these related … -
Date field dont autofill value Django
My browser (chrome and firefox) doesn`t autofill my Datefield, but in safari working example I inspected my html HTML field have value my view.py def get(self, request, slug): order = get_object_or_404(Order, order_number=slug) form = DirectorForm(instance=order) return render(request, 'edit_order.html', context={'form': form}) my forms.py widgets = {'order_date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'})} -
Setting Up Category and Forum and Loop it
I'm creating a forum software in Django and I'm having a hard time figuring out how to relate the forums table to the categories. I want to display this to the index page: Category 1 --forum 1 --forum 2 --forum 2 Category 2 --forum 1 --forum 2 --forum 3 These are my models: class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Forum(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='forums') def __str__(self): return self.name Here are my views: class HomeView(ListView): context_object_name = 'name' template_name = 'index.html' def get_context_data(self, *args, **kwargs): context = super(HomeView, self).get_context_data(*args, **kwargs) context['forums'] = Forum.objects.all() context['categorys'] = Category.objects.all() return context This is what I currently have on the home page, the only problem is, it's simply looping through all the categories and forums. I want the category to be looped in the first for loop, and in the second one to pull all the forums that belong to that category. {% for category in categorys %} --code {% for forum in forums %} --code {% endfor %} {% endfor %} How do I fix this so that it displays properly and the relation is correct? A category can have many forums but … -
How to set initial data in a FormMixin and DetailView
I want to create a comment form using generic foreignkey, but a having troubles with getting the initial data for object_id and content_type in the form ? class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type= models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object= GenericForeignKey() parent= models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE) content = RichTextField() time_stamp = models.DateTimeField(auto_now_add=True) Forms.py class CommentsForm(forms.ModelForm): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) content = forms.CharField(widget=forms.Textarea(attrs={ 'class':'form-control', 'cols':'4', 'rows':'3' })) class Meta: model = Comment fields = ['content','user','object_id', 'content_type'] Views.py class SongDetail(FormMixin, DetailView): model = Song form_class = CommentsForm def post(self, request, *args, **kwargs): obj = self.get_object() if not request.user.is_authenticated: return redirect('music:obj.get_absolute_url()') if form.is_valid(): form.save() return self.form_valid(form) -
No module named Crypto.Cipher Open EdX
Tried to import this code to our edx site encrypt data in python but it requires a package which is pycryptodome. Tried installing it using: pip install pycryptodome but it still shows an error everytime I call from Crypto.Cipher import AES . WARNING:enterprise.utils:Could not import Registry from third_party_auth.provider WARNING:enterprise.utils:cannot import name EnterpriseCustomerUser Traceback (most recent call last): File "./manage.py", line 120, in <module> startup.run() File "/openedx/edx-platform/cms/startup.py", line 19, in run django.setup() File "/openedx/venv/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/openedx/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 116, in populate app_config.ready() File "/openedx/edx-platform/cms/djangoapps/contentstore/apps.py", line 22, in ready from .signals import handlers # pylint: disable=unused-variable File "/openedx/edx-platform/cms/djangoapps/contentstore/signals/handlers.py", line 12, in <module> from contentstore.proctoring import register_special_exams File "/openedx/edx-platform/cms/djangoapps/contentstore/proctoring.py", line 19, in <module> from contentstore.views.helpers import is_item_in_course_tree File "/openedx/edx-platform/cms/djangoapps/contentstore/views/__init__.py", line 9, in <module> from .course import * File "/openedx/edx-platform/cms/djangoapps/contentstore/views/course.py", line 101, in <module> from Crypto.Cipher import AES ImportError: No module named Crypto.Cipher Sorry for a very vague question since I'm not really a python/django/open edx developer and was just tasked to support the project and did some heavy research but still no light. -
Django - Create and add multiple xml to zip, and download as attachment
I am learner, and trying to build code to in which user has option to download the zip file that contains multiple .xlm files, which are created on the bases of database. I have been able to create below code to download single xml file. But struggling to get multiple files packed in zipped format(for each row of database). import xml.etree.ElementTree as ET def export_to_xml(request): listings = mydatabase.objects.all() root = ET.Element('listings') for item in listings: price = ET.Element('price') price.text = str(item.Name) offer = ET.Element('offer', attrib={'id': str(item.pk)}) offer.append(price) root.append(offer) tree = ET.ElementTree(root) response = HttpResponse(ET.tostring(tree.getroot()), content_type='application/xhtml+xml') response['Content-Disposition'] = 'attachment; filename="data.xml"' return response -
Django: Retrieve all details of all Test model instances assigned to a User model
Following is my models.py models: from django.db import models from django.contrib.auth.models import User class Question(models.Model): question= models.TextField() optionA= models.CharField(max_length= 32) optionB= models.CharField(max_length= 32) optionC= models.CharField(max_length= 32) optionD= models.CharField(max_length= 32) answer= models.CharField(max_length= 6, choices= options, default= 'A') class Test(models.Model): name= models.CharField(max_length= 16) questions= models.ManyToManyField(Question) class TestTaker(models.Model): user= models.OneToOneField(User, on_delete= models.CASCADE) tests= models.ManyToManyField(Test) Following is my definition of home function that renders the website home inside views.py def home(request): try: tests= TestTaker.objects.filter(user= request.user).values('tests') print(tests.values) # tests= Test.objects.filter(user= request.user) return render(request, 'tests/home.html', {'tests': tests}) except: print('excepted') return render(request, 'tests/home.html') I want to extract the whole tests that are assigned to a logged in user. I can get only the test objects assigned to an authenticated user, but I want to be able to retrieve the whole of each test, along with it's questions. How can I do that? -
My first django app - how to import templates?
I am creating my first django app in django 3.1.1. There are video tutorials for old django versions and they don't always work... I want to create HTML pages for both home and about sections. I have already written some HTML files, but the def home(request): return render(request, 'home.html') doesn't want to work. I add my file tree for you to see the structure of files. RemoveBigFile ├── RBF1module │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── RemoveBigFile │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ ├── views.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── RemoveBigFile.sublime-project ├── RemoveBigFile.sublime-workspace ├── db.sqlite3 ├── manage.py └── templates ├── about.html └── home.html And that is the error message I get: TemplateDoesNotExist at / home.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.1 Exception Type: TemplateDoesNotExist Exception Value: home.html Django also asks me to put my templates in one of main django installation directories called templates and as far as I … -
how to connect to mongodb atlas through ssh in django
I'm trying to connect to remote mongodb database through ssh. I'm able to do it in Mongodb compass but not in my django project. Can someone please give me the correct configuration -
restrict access to the APIs just with my Android app and my vue.js web app
I'm new to Django Rest Framework. I want to restrict access to the APIs just with my Android app and my vue.js web app, without any user login. What is the standard way for doing this? -
Please help I cannot import django
enter image description here]1 pls tell me what I gotta do to fix this error -
Firewall restricting Django Server
I am running django server on my local ip (192.168.86.122:8000) but the windows firewall seems to block the connection. Any suggestion would be really helpful. -
Django queryset values list with annotated count of distinct related values
I have models Software and Domain described loosely as: class Software(models.Model) id = models.BigInteger(primary_key=True, db_index=True, null=False) company = models.ForeignKey('Company') domain = models.ForeignKey('Domain') type = models.CharField(null=False) vendor = models.CharField(null=False) name = models.CharField(null=False) class Domain(models.Model): id = models.BigInteger(primary_key=True, db_index=True, null=False) type = models.CharField() importance = models.DecimalField(max_digits=11, decimal_places=10, null=False) And I get a Software queryset with: qs = Software.objects.filter(company=c).order_by('vendor') The desired result should have an aggregated Domain importance with total count for each unique Software, i.e. [ { 'type': 'type_1', \ 'vendor': 'ajwr', | - unique together 'name': 'nginx', / 'domains': { 'total_count': 4, 'importance_counts': [0.1: 1, 0.5: 2, 0.9: 1] }, }, { ... }, ] I'm lost at trying to aggregate the importances separately. I annotate the original queryset with qs.annotate(importance=F('domain__importance')) and can get unique non-domain values with just a .order_by('name').values('type', 'vendor', 'name').distinct() but have no clue how to go forward from here. Do I need a subquery to do the importance aggregation? Would getting a separate queryset just for the related Domains make this easier (using some form of id__in with the Software qs)? Faster is better -
django login using email instead of username passing email but its checking username
I am unable to login with email but I am able to do it with username. How do I login with email instead of username. This is my html page : I tried to pass email instead of username but unable to login This is my views.py file: When i try to authenticate by change username to email, it is printing "invalid login details supplied!" This is forms.py: -
Django: "python manage.py runserver" not working
I am getting an error File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax when running python mange.py runserver error image from ubuntu terminal -
How to Host Python, Django, PostgreSQL Application on IIS 10
Hope Everyone will be fit and fine. I am trying to host my Django application on windows 2016 server IIS server. I had used Python, Django, pipenv as virtual environment and PostgreSQL as Database. I had tried almost tried everything available on the internet but till now I am not successful. maybe I have not got the perfect tutorials or find the correct one to host the Django Application. Please help me host the Django Application on IIS 10. I will be really grateful for the help Thanks in Advance. Regards Sachin -
Trying to edit post: Reverse for 'edit' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/edit/(?P<pk>[0-9]+)$']
I am trying to be able to edit the question with an tag which references my edit_post function in my views.py. I think the issue is because I haven't passed in the context into the right view for it to be displayed but I am not sure how to fix it. Getting this error - Reverse for 'edit' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P[^/]+)/edit/(?P[0-9]+)$'] Views.py @login_required(login_url='sign_in') def dashboard(request, *args, **kwargs): username = request.user.username filtered_questions = Question.objects.filter(user_id=username) context = { 'filtered_questions': filtered_questions, } return render(request, 'users/dashboard.html', context) def edit_post(request, pk): question = Question.objects.get(pk=pk) if rerquest.method == 'POST': form = QuestionForm(request.POST, instance=question) if form.is_valid(): form.save() question.user = request.user return redirect('/') else: form = QuestionForm(instance=question) else: form = QuestionForm(instance=question) context = { 'form': form, 'question': question, } return render(request, 'users/edit_question.html', context) Urls.py urlpatterns = [ path('<username>', views.dashboard, name='dashboard'), path('<username>/upload', views.upload, name='upload'), path('<username>/edit/<int:pk>', views.edit_post, name='edit') ] Template with the edit question button <a href="{% url 'edit' question.pk %}"> -
Download link or View link to a file
i have a list of document from my models, one of the fields is a path to the url. how can i make a button such that when i click it, it opens the file. I have tried some methods but it didn't work well Thanks This is the html {% for document in document_lists_doc %} <tr> <th>{{forloop.counter}}</th> <th>{{document.date}}</th> <th>{{document.name}}</th> <th>{{document.url}}</th> <th>{{document.memo}}</th> </tr> {% endfor %} This is the Model class PurchaseOrderDocument(models.Model): po_number = models.ForeignKey(PurchaseOrder, on_delete=models.SET_NULL, null=True) date = models.DateField() name = models.CharField(max_length=100) url = models.FileField(upload_to='static/files/', null=True, max_length=500) memo = models.CharField(max_length=200) def __str__(self): return self.name kindly check the image, i will like that path to be a link to open the file when clicked -
Django Rest Framework - Fill model field with previous entry value
I'm starting to build a REST API with Django for studies proposes and I kinda encounter an obstacle to me. I have a model like class ExampleModel(models.Model): name = models.CharField(max_length = 36) class_type = models.CharField(max_length = 10) timestamp = models.PositiveIntegerField() last_timestamp = models.PositiveIntegerField() and a serializer with: class ExampleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ExampleModel fields = '__all__' read_only_fields = ['timestamp', 'last_timestamp'] def create(self, validated_data, **kwargs): validated_data['timestamp'] = int(datetime.timestamp(datetime.now())) #validated_data['last_timestamp'] = ... return ExampleModel.objects.create(**validated_data) I would like to fill the "last_timestamp" field with the "timestamp" value of the last entry that matches with the "class_type" of the current one. Using the psycopg2 lib a simple solution could be: last_entry_query = 'SELECT max(id) FROM example_table WHERE class_type = %s' % current_type get_timestamp = 'SELECT timestamp FROM example_table WHERE id = (%s)' % last_entry_query cur.execute(get_timestamp) try: ts = cur.fetchone()[0] except: ts = 0 and use the "ts" value to add to the next entry, I'm kinda new with the Django and DRF, but I assume that is a proper way to do that correctly or at least more pythonic, if anyone could help it would be amazing. -
How to get OTP token for an existing user in django using django-two-factor-auth
I am writing selenium tests for django. I want to login a user with OTP through UI using selenium. After login , I get the setup page where I am supposed to enter a 6 digit token generated by google authenticator. django-two-factor-auth stores a secret key per user in table otp_totp_totpdevice . I assume google authenticator is supposed to use this key to generate the token. Following is what I have tried so far: it generates a wrong token. import hmac, base64, struct, hashlib, time def get_hotp_token(secret, intervals_no): key=base64.b64decode(secret,validate=True) msg = struct.pack(">Q", intervals_no) h = hmac.new(key, msg, hashlib.sha1).digest() o = h[19] & 15 h = (struct.unpack(">I", h[o:o + 4])[0] & 0x7fffffff) % 1000000 return h def get_totp_token(secret): return get_hotp_token(secret, intervals_no=int(time.time()) // 30) -
How can I get the image to show in the img container, using Django template tags?
So I am at the last couple details of my portfolio website, and everything has gone relatively smoothly. I have not had an issue with images before, but this time I am using a {% for loop %} to iterate over the code for the card and I just have the variable template tags that create a new object every time I add something new in the django admin interface. I feel like there is some small detail I am just completely missing, because I had it working at one point, but then decided to do the iteration instead of hard-coding it in, and it just won't show up. Another pair of eyes would be nice. This is the section of my index.html: {% block content %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Jordan Miracle</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/static/portfolio/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <body> <div class="jumbotron text-center ui-datepicker-next-hover" style="margin-bottom:0"> <div class="align-center"> <img src="{% static 'portfolio/mylogo.png' %}" id="img-bastet" class="img-fluid" alt="Jordan and Bastet"> </div> <h1><p style="font-family: 'Ubuntu Mono', Monospaced, monospace; font-size: medium;">Developer and Aspirant Data Scientist</p> </div> <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <a class="navbar-brand" href="{% url 'home' %}">Home</a> <button class="navbar-toggler" … -
Docker-Compose with neo4j and Django runs into connection error
I'm trying to run my Django application with Neo4j using the django_neomodel plugin but for some reason it seems like my docker compose file may be set up incorrectly: version: '3' services: db: image: postgres # Change to dynamic creds creation this is fine for local deployment for now environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres neo4j: image: neo4j restart: unless-stopped ports: - 7474:7474 - 7687:7687 volumes: - ./conf:/conf - ./data:/data - ./import:/import - ./logs:/logs - ./plugins:/plugins environment: # Raise memory limits - NEO4J_dbms_memory_pagecache_size=1G - NEO4J_dbms.memory.heap.initial_size=1G - NEO4J_dbms_memory_heap_max__size=1G - encrypted=False web: environment: - DB=POSTGRES build: . image: stupidfatcat/herlocksholmes command: python herlocksholmes/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "127.0.0.1:8000:8000" depends_on: - db - neo4j But whenever I run python manage.py install_labels I run into: File "/usr/local/lib/python3.8/site-packages/neobolt/direct.py", line 843, in _connect raise ServiceUnavailable("Failed to establish connection to {!r} (reason {})".format(resolved_address, error)) neobolt.exceptions.ServiceUnavailable: Failed to establish connection to ('::1', 7687, 0, 0) (reason [Errno 99] Cannot assign requested address) So it seems like my web container can't reach the neo4j container. What am I doing wrong?