Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to configure djongo for production with admin account?
I managed to get djongo working in my local computer but when I push it to production, I need to set up an admin account for mongo so that my DB doesnt get hacked (again, sigh). Ive searched for a solution for a couple of days, without success. This is currently the code I have, but its not working: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'db_name', 'HOST': 'localhost', 'USERNAME': 'username', 'PASSWORD': 'password', } } 1) How can I configure djongo to access a DB with a username/password? I am only getting errors telling me that it wasnt able to log in to mongo. 2) Ive read a bit about "mongoengine", would you recommend I use that instead of djongo? Why? -
local variable 'random' referenced before assignment
import random from random import randrange from random import randint def function(request): random = random.randint(1000, 9999) print("random :",random) return HttpResponse(random) -
How to send pytest coverage report via email?
I am using pytest framework and pytest-cov plugin to get the coverage report generated, which generates a coverage report file inside htmlcov directory after the test cases are executed, is there a way where I can also send this report file as an attachment while the test cases are executed? -
django.db.migrations.exceptions.NodeNotFoundError: Migration admin.0004_auto_20200309_0721 dependencies reference nonexistent
I created a project with Django3 and i'm using sqlite3 database. When i try to migrate the project initiallly it raising the error like this : django.db.migrations.exceptions.NodeNotFoundError: Migration admin.0004_auto_20200309_0721 dependencies reference nonexistent parent node ('main', '0001_initial') although there is no any migration dependencies before. I search for this error on google but nothing worked for me . How can i solve this issue ? I will be glad if i get solution of this. -
Django Rest Framework sql string query
I know if it is very easy to add API filtering to a rest API in Django. /api?name=joseph&age=5. # I already have that however, I am using a react package to generate the query, and it generates SQL string as such: "name = 'joseph' AND age = 5" I wonder what would be the easiest way to filter a table with SQL-string. The query could be nested with ORs and ANDs and NOTs. Please help .. -
Why doesn't Django's built-in login work?
so I was trying to use Django's built-in login with the codes below, but then I ran into a problem. With url '.../login' I was able to access the login page, but then when I typed in the username and password (of my superuser account), it did not redirect to any page. Moreover, I realized that I was not even logged in, when I tried to access the admin page and it showed me the login window(?). This is the code in my urls.py in the main folder. urlpatterns = [ # other stuff , path('', include("django.contrib.auth.urls")) } And this is my login.html file {% extends 'main/base.html' %} {% block title %}Log In{% endblock %} {% load crispy_forms_tags %} {% block content %} <form mehtod='post' class="form-group"> {% csrf_token %} {{form|crispy}} <p>Don't have an account? Create one <a href="/register">HERE</a></p> <button type="submit" class="btn btn-success">Log In</button> </form> {% endblock %} Finally, I've added the code below to my settings.py LOGIN_REDIRECT_URL = "/" LOGOUT_REDIRECT_URL = "/" As well, what I've notices is that as soon as I typed in the username and password and hit 'Log In' button, the url turned into this: http://127.0.0.1:8000/login/?csrfmiddlewaretoken=qcPDO9hPSpFTIXyz8f9Tv22qUQttqngKaauJu5HXlRzHtPyqyZ7kPgpWugEmbBGI&username=mySuperUser&password=myPassword You should notice that the username and password appeared in … -
Is it possible to create a symbolic link or shortcut when importing modules?
I am using a third party app, post-office, in my Django project. I want to make changes to this app rather than including it in requirements.txt, so have added the code into my project: -- my-project -- my-app -- post-office Because I'm doing this for a number of apps, I'd actually like to keep them all in a vendor folder: -- my-project -- my-app -- vendor -- post-office When importing modules from this app, I know the correct path is then vendor.post-office.[module]. However, the post-office app itself uses post-office.[module] when it imports modules between directories. Rather than rewriting all the imports from post-office. to vendor.post-office. is there an easy way to create a symbolic link or shortcut? -
Django to_representation and filter_fields err: TypeError: 'Meta.fields'
i'm trying to store the value of a property called title in a property called _id which would be the same input as title, just lower case and with no spaces, simple replace() but I've tried instantiating it to_representation(). When I try to add _id to my filter_fields I get the err below, remove it and it runs, but i need to the property _id filter_fields = ('title', '_id',) <--- the _id cause the err TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: _id models.py class Portfolio(models.Model): created_at = models.DateTimeField() title = models.CharField(max_length=255) description = models.TextField() link = models.CharField(max_length=300) img = models.CharField(max_length=255) def __str__(self): return self.title serializer.py here is where I try to instantiate it by overriding to_representation() class PortfolioSerializer(serializers.ModelSerializer): class Meta: model = Portfolio fields = ('created_at', 'title', 'description', 'link', 'img', ) def to_representation(self, instance): data = super().to_representation(instance) data['_id'] = instance.title.lower().replace(" ", "_") return data api.py class PortfolioList(ListAPIView): queryset = Portfolio.objects.all() serializer_class = PortfolioSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('title', '_id',) -
How to overcome "Package 'whitenoise' requires a different Python: 2.7.16" error?
I had already installed python 3.8.2 in my MX linux-19. But when i try to install django-heroku in pycharm it said ERROR: Package 'whitenoise' requires a different Python: 2.7.16 not in '>=3.5, <4 then i install python 2.7.16 but not uninstall the previous latest one. After installing it, It again occurs the same error. What should i do now? -
Can I Upload a Cropped Image To Django?
I am using jquery-cropper to try to crop images in a browser for my django application. It works well until I have to upload it. This is due to the fact that I cannot find a way to upload the cropped image to django. I am using a ver basic django model for the file upload. Does anyone have any suggestions? -
cronjob in docker container cannot connect to other container
I want to use cronjob to run a script, which is to fetch data from news api and feed it into postegres which is located in other container. so the simplified architecture is app(in container) -> postegres(in container) the cronjob script is inside app, and it will fetch data and then send to postegres. in my crontab is * * * * * cd /tourMamaRoot/tourMama/cronjob && fetch_news.py >> /var/log/cron.log 2>&1 i can run it successfully by manually run the script, but when i put it in crontab , it shows the error. File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/dist-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? seems it only look for database locally if use crontab, how can i set it to put data into other container like i manually run the script? Info: my docker container for app is Ubuntu version 18.04 , and the following is my docker file for app FROM ubuntu:18.04 MAINTAINER Eson ENV PYTHONUNBUFFERED 1 ENV … -
Form from ModelForm kept on showing up 'QuerySet' object has no attribute '_meta'
I need help on above error with below django modelform : models.py class Problems(models.Model): biodata = models.ForeignKey(Biodata, on_delete = models.CASCADE, default='') problem = models.CharField(max_length=200) notes = models.CharField(max_length=300) status = models.CharField(max_length=30) date = models.DateField() def __str__(self): return self.problem forms.py: class Problem_Form(forms.ModelForm): class Meta(): model = Problems fields = '__all__' views.py def index(request,id): problem = Problems.objects.all().filter(biodata=id) problem_form = Problem_Form(instance=problem) context = {'problem_form':problem_form} return render(request, 'index.html', context) index.html <form method="POST"> {% csrf_token %} {{ problem_form.as_table }} </form> When run the code above, the message 'QuerySet' object has no attribute '_meta' kept on showing up. Please help to resolve this. -
Problem with Django session using cors headers
I will do my best to explain this. I have this App A on Django and I'm using rest_framework on it. I have an endpoint to login /auth/login. I test it in the DRF view and it works perfectly. Here is the code # view.py from django.contrib.auth import authenticate, login from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.permissions import AllowAny from rest_framework import status @api_view(['POST']) @permission_classes([AllowAny,]) def api_login(request): username = request.data["username"] password = request.data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) Now, I have this App B on Express and it has a login form to log the users using the endpoint from App A. ... const axios = require('axios') axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true ... router.post('/login', (req, res) => { axios.post('http://127.0.0.1:8000/auth/login/', req.body) .then(rv => { console.log('login', rv) res.send('Login') }) .catch(err => { console.log('error', err) res.send('Error') }) }) ... When I try to log in form App B, it kind of works. App A receives the data, the user is authenticated, it returns a status 200 code, it even saves the session on the database but there is no sessionid cookie created as when … -
AttributeError Django rest framework
.save process is ok and data is reflected on DB but i am getting this error. "AttributeError: Got AttributeError when attempting to get a value for field asset_list on serializer TransactionSerializer." Models transaction_main from V1.accounts.models.employee_main import Employee class Transaction(CreatedModified): transaction_id = models.BigAutoField(primary_key=True) employee_from = models.ForeignKey( Employee, related_name='employee_from_transactions', related_query_name='employee_from_transaction', default=None, on_delete=models.CASCADE ) employee_to = models.ForeignKey( Employee, related_name='employee_to_transactions', related_query_name='employee_to_transaction', default=None, on_delete=models.CASCADE ) location_from = models.CharField(null=True, blank=True, max_length=255) location_to = models.CharField(null=True, blank=True, max_length=255) transaction_type = models.CharField( max_length=3, choices=TransactionType.choices, default=None ) date_issued = models.DateField(auto_now=False, auto_now_add=False) remarks = models.CharField(null=True, blank=True, max_length=255) transaction_main_asset from V1.transactions.models.transaction_main import Transaction from V1.assets.models.asset_main import Asset class TransactionAssets(CreatedModified): transaction = models.ForeignKey( Transaction, related_name='tr_assets_transactions', related_query_name='tr_assets_transaction', default=None, on_delete=models.CASCADE ) asset = models.ForeignKey( Asset, related_name='assets_transactions', related_query_name='assets_transaction', default=None, on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True, editable=False) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, db_index=True, editable=False, on_delete=models.SET_NULL, related_name="tr_assets_created") Serializers transaction_asset_serializer from V1.transactions.models.transaction_main_assets import TransactionAssets class Transaction_AssetsSerializer(serializers.ModelSerializer): class Meta: model = TransactionAssets fields = ('asset',) transaction_serializer from V1.transactions.models.transaction_main import Transaction from V1.transactions.models.transaction_main_assets import TransactionAssets from V1.transactions.serializers.transactions_asset_serializer import Transaction_AssetsSerializer class TransactionSerializer(serializers.ModelSerializer): asset_list = Transaction_AssetsSerializer(many=True) class Meta: model = Transaction fields = ( 'employee_from', 'employee_to', 'location_from', 'location_to', 'transaction_type', 'date_issued', 'remarks', 'asset_list' ) def create(self, validated_data): asset_data = validated_data.pop('asset_list') transaction = Transaction.objects.create( employee_from = validated_data['employee_from'], employee_to = validated_data['employee_to'], location_from = validated_data['location_from'], location_to = validated_data['location_to'], transaction_type … -
Generic detail view createjob must be called with either an object pk or a slug in the URLconf
I'm trying to create a view that check whether if the user is in the manager model or not. This checks the user if they are included so they will be able to post a task. I have created a view in other to this. however the test_func method is not working. When I create a new task it will gives me an error of Generic detail view createjob must be called with either an object pk or a slug in the URLconf.I have already created get_absolute_url in my Job model to reverse to a detailview. CAn anyone help me out? views.py: class createjob (LoginRequiredMixin,UserPassesTestMixin,CreateView): model = Job fields = ['member','title', 'description', 'file'] def form_valid(self,form): form.instance.manager=manager.objects.get(manager=self.request.user) return super().form_valid(form) def test_func(self): return self.get_object().manager == self.request.user urls.py: urlpatterns = [ path ('new/', createjob.as_view(),name='create-job'), path ('team/',teamview.as_view(), name='team-view'), path('<int:pk>/',jobdetail.as_view(),name='job-detail'), path ('created/',createdjobs.as_view(), name='create-job-manager'), path ('',jobs.as_view(),name='view-jobs') Models.py: from django.db import models from profiles.models import User from django.urls import reverse # Create your models here. class Points (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0, null=False) def __str__(self): return self.user.username class Profile (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png',upload_to='profile_pics') def __str__(self): return f'{self.user.username}Profile' class Manager (models.Model): name = models.CharField(max_length=30, blank=True, null=True) manager = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): … -
How do I filter post from users from the admin page based on a date range?
My CBV in views.py class PostListView(ListView): queryset = Post.objects.filter(created__range=["2020-03-09", "2020-03-31"]) template_name = 'main/problems.html' context_object_name = 'posts' ordering = ['-created'] I want an admin to be able to set created__range=["2020-03-09", "2020-03-31"] from the admin page because this date changes and doesnt follow any sort of pattern. -
Django Image not uploading
I am unable to have the file in a inlineformset_factory actually upload to the DB or static folder. The form completes then executes succeful_url. Im just not understanding why this isn't uploading the files after submit. Any help is greatly appreciated. Model.py class Listing(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4,editable=False) agent = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING) class Images(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to="listing/images/") listing_id = models.ForeignKey(Listing, on_delete=models.DO_NOTHING) Forms.py class ListingImage(forms.ModelForm): class Meta: model = Images exclude = () ListingImageFormSet = inlineformset_factory(Listing, Images, fields=['image'], form=ListingImage, extra=2) Views.py class AgentNewListing(CreateView): model = Listing fields = ['agent'] template_name = 'agent/new_listing.html' success_url = '/agent/dashboard/' def get_context_data(self, **kwargs): data = super(AgentNewListing, self).get_context_data(**kwargs) if self.request.POST: data['listing_form'] = ListingImageFormSet(self.request.POST) else: data['listing_form'] = ListingImageFormSet() return data def form_valid(self, form): context = self.get_context_data() listingform = context['listing_form'] with transaction.atomic(): form.instance.agent = self.request.user self.object = form.save(commit=False) if listingform.is_valid(): listingform.instance = self.object listingform.save() return super(AgentNewListing, self).form_valid(form) def dispatch(self, request, *args, **kwargs): if not is_valid_agent(self.request.user): return redirect('/agent/signin/') return super(AgentNewListing, self).dispatch(request, *args, **kwargs) Template.htlm {% extends 'agent/agent_base.html' %} {% block agent_body %} {% load crispy_forms_tags %} <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">New Listing</h1> </div> <div class="col-sm-6 col-lg-6 ml-2"> <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form|crispy }} <table … -
Dynamic reverse related lookup in ModelForm when using UpdateView
I have a ModelForm BaseQuizForm for Model Quiz which I need to allow updates of reverse related objects Questions in. The issue is that it is not updating the reverse related objects. It works with the CreateView but does not work with the UpdateView. What can I do to make this work with my UpdateView? class Quiz(models.Model): title = models.CharField() category = models.ForeignKey( Category, on_delete=models.CASCADE) class Question(models.Model): quiz = models.ManyToManyField(Quiz) category = models.ForeignKey( Category, on_delete=models.CASCADE) class BaseQuizForm(forms.ModelForm): questions = forms.ModelMultipleChoiceField( queryset=None, required=False, label="Questions", widget=forms.CheckboxSelectMultiple, ) class Meta: model = Quiz def __init__(self, *args, **kwargs): self.user = (kwargs.pop('user', None)) super(BaseQuizForm, self).__init__(*args, **kwargs) super_role = self.user.role subs_id = self.user.subordinates.values_list('role', flat=True) sub_roles = EmployeeType.objects.filter(pk__in=subs_id) cats = Category.objects.filter(groups=super_role) | Category.objects.filter(groups__in=sub_roles) if self.instance.pk: self.fields["questions"] = forms.ModelMultipleChoiceField( queryset=self.instance.question_set.all().select_subclasses(), widget=CheckboxSelectMultiple) else: self.fields["questions"] = forms.ModelMultipleChoiceField( queryset=Question.objects.filter(category__in=cats).select_subclasses(), widget=CheckboxSelectMultiple) def save(self, commit=True): quiz = super(BaseQuizCreateForm, self).save(commit=False) quiz.save() quiz.question_set.set(self.cleaned_data['questions']) self.save_m2m() return quiz -
ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17)
I built an website in Django & went to go upload it to aws using zappa following this tutorial. I am running a virtual environment using python3.8.1. When I deploy using Zappa I get this error: Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code. Checking the logs using zappa tail I get this: ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). When I check the sqlite3 version I get this: (env)$ python Python 3.8.1 (default, Dec 27 2019, 18:06:00) >>> import sqlite3 >>> sqlite3.sqlite_version '3.31.1' When I check for just sqlite (just to be sure) I get this: >>> import sqlite Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'sqlite' When I check the Django version I get this: >>> django.VERSION (3, 0, 4, 'final', 0) I tried to use these resources to solve it but couldn't get anywhere (I think because I am new & confused): How to upgrade sqlite 3.8.2 to >= 3.8.3 How to upgrade sqlite3 version in Python from 3.7.17 to > 3.8 Using SQLite3 with Django 2.2 and Python 3.6.7 … -
How can I set subapps in django?
I have two apps under one project and decide to move these two apps under apps parent directory. My current structure is, project - app1 - app2 - project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py New structure I am trying to have, project - templates - static - apps - app1 - app2 - project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py Following to this, How to keep all my django applications in specific folder I edited my settings.py from os.path import abspath, basename, dirname, join BASE_DIR = dirname(dirname(abspath(__file))) PROJECT_ROOT = dirname(__file__) sys.path.insert(0, join(PROJECT_ROOT, 'apps')) INSTALLED_APPS = [ .... 'apps.app1.apps.App1Config', 'apps.app2.apps.App2Config', ] I got an error that ModuleNOtFoundError: No module named 'app1' Where should I have to edit to fix this issue? -
Run a if clause on a @receiver in Django
I have a model Client which uses a @receiver to update its fields whenever a User is created. class Clients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") city = models.CharField(max_length=200, verbose_name="Cidade") postal = models.CharField(max_length=8, validators=[RegexValidator(r'^\d{4}(-\d{3})?$')], verbose_name="Código Postal") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Meta: verbose_name_plural = "Clientes" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Clients.objects.create(user=instance) instance.clients.save() Is there a way to only run this if the user created belongs to a specific group? -
Using Django form FileField with custom file
I'm creating a form builder for my project. It builds forms dynamically according to fields specified in database. There are 3 tables: form, form fields and form fields values. Now I'm trying to bind data from form values to form fields. It works well, for example like this: if (field.field_type == 'long_text'): new_field = forms.CharField(label=field.label, initial = value, required=False, widget=forms.Textarea(attrs={'class': 'form-control'})) But this doesn't work for FileField: new_field = forms.FileField(label=field.label, required = False, initial = initialData) As far as I understand, "initial" data has to be in certain format: this has to be an object with url and name attributes This is what I do: try: ''' data is stored in JSON {url:'', name:''} format ''' valueData = json.loads(value) initialData.initial = valueData['name'] initialData.url = valueData['url'] initialData.name = valueData['url'] except: pass new_field = forms.FileField(label=field.label, required = False, initial = initialData) Form is still empty. No "clear" checkbox, no url to click and "no file selected". What can I do to make this file input work? Do I need to emulate model's filefield? -
Looking for read-write lock in Django using PostgreSQL, e.g., SELECT FOR SHARE
I am locking for a read-write lock in Django, using PostgreSQL. I know select_for_update On top, I need SELECT FOR SHARE I founds this super old Django-ticket I couldn't find any third party library implementing this for Django Now I am wondering: Is there a good reason this was not implemented in the Django-ORM? Does anyone know any third party library for this? Or any easy work around? -
Translating Django site into multiple languages?
I have a a Django site with 10-15 models/tables. Each row needs to be translated into at least 4 or 5 languages. What is the most efficient way of implementing localization? I've read you can use .po files. But one would have to mark every single single that needs to be translated, which seems tedious. There are modules that create additional fields for additional languages. This seems to blown up the DB unreasonably. -
Django, ModelChoiceField() and initial value with formset not working
I have the form below in my forms.py. I am setting the self.fields['start'] to ModelChoiceField with queryset=Flow.objects.all(). class GroupForm(ModelForm): class meta: model = Group fields=['conditionn', 'start'] def __init__(self, *args, **kwargs): super(GroupForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.fields['condition'] = forms.CharField(label='Post Condition', widget=forms.TextInput( attrs={'placeholder': 'The system displays the "Home" button'})) #to check what is in the initial initial = kwargs.get('initial', {}) print("wow",initial) self.fields['start'] = forms.ModelChoiceField(label='Success or Abort', widget=forms.Select, queryset=Flow.objects.all()) GroupInlineFormSet = inlineformset_factory(ParentModel, BoundedFlowGroup, form=BoundedFlowGroupForm) In my views, I have class UpdateGroup(Updateview): ... def get_context_data(self, **kwargs): print(self.object) context = super(UseCaseUpdateView, self).get_context_data(**kwargs) if self.request.POST: .... else: context['Another_form'] = AnotherFormSet(instance=self.object, prefix='group') groupQuerySet=context['Another_form'].instance.group_set.all() flowQuerySet=basicGroupQuerySet[0].flow_set.all() context['boundedGroupNested_form'] = BoundedGroupNestedFormSet(initial=[{'start':flowQuerySet}], instance=self.object, prefix='boundedFlowGroup') return context .... Now, in the view, I am trying to set the start initial values with initial=[{'start':flowQuerySet}]. When I print out the flowQuerySet I got the correct values I would need for the start field. However, when I view my render template, I am see all the instances of Flow instead of the ones from the flowQuerySet. So, If the are 1,2,3,4,5,6 Flows and flowQuerySet has only 5, 2,1 - I want only 5,2,1 as selection option in the ModelChoiceField of start, but I am still getting 1,2,3,4,5,6. How do I set the model's instances for …