Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin returns 404 on POST, 200 on GET
On production server, when I try to edit/create an object then saving fails, returning 404. This only occurs for POST requests, GET requests (loading the page) work fine. Django is deployed via cPanel and WSGI, DEBUG is False (though it does not work even when it's set to True) I have deployed the Django app with cpanel, running in a virtualenv. This only seems to happen for a model that uses FileField for file upload, other models can be changed/created just fine. The model: def get_image_path(instance, filename): name, ext = filename.split('.') return f'images/{instance.advert_id}/{name}.{ext}' class AdvertImage(models.Model): advert = models.ForeignKey(Advert, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_path) URL conf: urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] + i18n_patterns( path('admin/', admin_site.urls), # ... other views.... prefix_default_language=False ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Navigate to domain.com/admin/colli/advertimage/1/change/ - the page loads correctly. Fill the form, click save: Using the URLconf defined in Colli.urls, Django tried these URL patterns, in this order: i18n/ admin/ [name='home'] advert/<slug:slug> [name='detail'] tagauks [name='admin_list'] tagauks/lisa [name='insert'] tagauks/muuda/<int:pk> [name='edit'] tagauks/kasutaja/<int:pk> [name='user_edit'] tagauks/save_image [name='save_image'] accounts/login/ [name='login'] accounts/logout/ [name='logout'] api/ ^media/(?P<path>.*)$ The current path, colli/advertimage/1/change/, didn't match any of these. The model should be saved and no 404 should occur. Other models, that do not use FileField, … -
How to make known field specified for User in django?
I made a lot of changes in my code. But whenever I makemigrations it is giving me same error of Unknown field(s) (Id_card_number) specified for User forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True)._unique = True Id_card_number = forms.CharField(max_length=15, required=True)._unique = True class Meta: model = User fields = ['username','email','password1','password2','Id_card_number'] views.py from django.contrib.auth import get_user_model UserProfile = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) models.py from django.db import models from django.contrib.auth.models import AbstractUser class UserProfile(AbstractUser): Id_card_number = models.CharField(max_length=15) admin.py from django.contrib.auth.admin import UserAdmin admin.site.register(UserProfile, UserAdmin) settings.py AUTH_USER_MODEL = 'users.UserProfile' -
Allow Only Specific users and superuser to edit a particular field in model
I have a model called test. Test models have three fields - Question, answer, verified. admin.py file model = Test def get_fields(self, request, obj=None): fields = ['question','answer','verified'] if request.user.is_superuser: fields.append('verified') return fields This code only allows the superuser to edit the verified record. But what I want is I have to give permission to some of the users to edit this field. -
How to save the list obtained from checkbox in django Modelform in databsae
Here, I am trying to save the multiple items checked from my form into the database using django Modelform. I got the list of item using the query but I couldn't save the data. Everything else works fine, the data from other fields are being saved in the database. How can I save these multiple items I got from checkbox? models.py class MyModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) skills = models.ManyToManyField(Skills, blank=True, null=True) facility = models.ManyToManyField(Facility, blank=True, null=True) forms.py class AddMyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' views.py def my_view(request, slug): if request.method == 'POST': form = AddMyModelForm(request.POST or None) if form.is_valid(): selected_skill = Skills.objects.filter(id__in=request.POST.getlist('skill')) selected_facility = Facility.objects.filter(id__in=request.POST.getlist('facility')) form.save_m2m() return redirect('/') else: form = AddMyModelForm() context = {'form': form} return render(request, 'template.html', context) template <form action="{% url '...' type.slug %}" method="post"> {% csrf_token %} <h3>Choose the below skills:</h3> {% for skill in skills %} <input type="checkbox" name="skill" id="skill-{{skill.id}}" value="{{skill.id}}"> <label for="skill-{{ skill.id }}">{{skill.title}}</label> {% endfor %} <h3>Choose the facilities below:</h3> {% for facility in facilities %} <input type="checkbox" name="facility" id="facility-{{facility.id}}" value="{{ facility.id }}"> <label for="facility-{{facility.id}}">{{ facility.title }}</label> {% endfor %} <button type="submit">Submit</button> </form> -
Verify record should only visible to admin not other users
I have to display the Verified field only to admin and to specific users and not to all users in list_display in admin.py file If I write list_display = ('question_name','type','verified') It is visible to all users and I have to hide this verified field to specific users and show to specific users. Can Anyone Please Help Me Out of this problem...? This is admin.py file class TestAdmin(admin.ModelAdmin): search_fields = ['question_name','type','added_by__username'] list_filter = ['type'] list_display = ('question_name','type') readonly_fields = ('added_by','date',) list_per_page = 20 def save_model(self, request, obj, form, change): if not obj.pk: # Only set added_by during the first save. obj.added_by = request.user super().save_model(request, obj, form, change) model = C_lang def get_fields(self, request, obj=None): fields = ['added_by', 'type', 'question_name', 'code', 'output', 'date'] if request.user.is_superuser: fields.append('verified') return fields Here is Models.py class Test(models.Model): class Meta: verbose_name_plural = 'C Language' type_choices = [ ('----', '----'), ('A', 'A'), ('B', 'B'), ] added_by = models.ForeignKey(User, null=True, blank=False, on_delete=models.SET_NULL) type = models.CharField(max_length=50,default='----',choices=type_choices) question_name = models.CharField(max_length=50, default='', validators=[MinLengthValidator(4)]) Ans = models.TextField(max_length=5000, default='') date = models.DateTimeField(default=now, blank=False) verified= models.BooleanField() -
what is the best and fast way to deploy django in a centos server?
I want to deploy Django in my centos server, and I don't know how? and do you know which panel is better for background server and this have auto-install and config? -
TypeError at /reg/ save() got an unexpected keyword argument 'force_insert'
I created a blog app in Django 2.2. And now I have a problem with registration users. The result gave TypeError at /reg/ save() got an unexpected keyword argument 'force_insert' .These are my views.py and models.py code: def register(request): if request.method == "POST": form = UserOurRegistration(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f"Akkaunt {username} muvaffaqiyatli ravishda yaratildi, akkauntga kirish uchun login va parolingizni kiriting") return redirect('user')``` And this is code of models.py: `from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) img = models.ImageField(default='default.jpg', upload_to='user_images') def __str__(self): return f'Foydalanuvchi {self.user.username} profili' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) image = Image.open(self.img.path) if image.height > 64 or image.width > 64: resize = (256, 256) image.thumbnail(resize) image.save(self.img.path)` i tried to rewrite code 3 times, searched in the internet to solve this problem, but I can't solve it. If you can, help me please. -
Django/Heroku: ModuleNotFoundError: No module named 'dj_database_url
In my requirements.txt: dj-database-url==0.5.0 psycopg2-binary==2.7.7 In setting.py import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) When I run: heroku run python manage.py migrate Error: import dj_database_url ModuleNotFoundError: No module named 'dj_database_url' I have also tried running: heroku run pip install dj-database-url It gets installed correctly, but the error is still there. -
Django: No module named 'project'
I was working on a Django project on my work laptop. Then I cloned the project to my work laptop and I'm getting a very weird error when I try to run any command, such as python manage.py runserver: 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 "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/db/utils.py", line 219, in close_all for alias in self: File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/db/utils.py", line 213, in __iter__ return iter(self.databases) File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/jmetz/miniconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in … -
Django - How to exclude a list of numbers from a QuerySet?
I have a list of integers: numbers = [1, 2, 3, 4] I have a model, MyModel, with primary keys ranging 1 to 1000 I would like to exclude the models with primary keys in the list 'numbers' from MyModel during a QuerySet: MyModel.objects.exclude(pk in numbers) The above doesn't work. What's the best way to do so? -
ContentType matching query does not exist on django 2.2
I have been using django to build a Blog, and when i tried to make a comment section under each post i get the comment icon(where i can type some comments) but when i post the comment i get the error straight away, which is "ContentType matching query does not exist". I tried to find the problem on stack and youtube but they said that solving this problem requires experience on dumpdata class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1,null=True,on_delete=models.SET_NULL) content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type','object_id') content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) objects = CommentManager() def blog_post_detail_view(request,slug): instance = get_object_or_404(BlogPost, slug=slug) share_string = quote_plus(instance.content) initial_data = { 'content_type':instance.get_content_type, 'object_id':instance.id } form = CommentForm(request.POST or None,initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') new_comment, created = Comment.objects.get_or_create( user = request.user, content_type = content_type, object_id = obj_id, content = content_data ) comments = instance.comments template_name = 'blog/detail.html' context = { "object":instance, 'comments': comments, 'share_string':share_string, 'comment_form':form } return render(request,template_name,context)from django import forms from .models import Comment class CommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) content = forms.CharField(widget=forms.Textarea) So basically i should have gotten my comment posted but instead i get that error:"ContentType matching query does not … -
Why django uses "ModelName.objects" to all model related function
Why django uses ModelName.objects to call all related function? There is no any other way to call these using only ModelName. To get all posts we use Post.objects.all() -
How can i work on 2 models in a single Django view?
I have a Django app where users upload images and the images will be processed and saved in 2 models, the processed will be in a model and the preprocessed in another model. the processing function is called by just main(image_01.png) so the upload/analyse view will be with a formset right? as formsets act on 2 models/forms. so how can i really do this is just calling model.preprocessed.main() after calling the .save(commit=false) ? how can I write this effectively ? is there a better way to write this? and is there any example code? -
How to build an invoice system with custom features below using DJANGO
I am building a side project invoice app. I have an inquiry in regard with creating the invoice system. models.py class Product(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) price = models.DecimalField(decimal_places=2, max_digits=10) quantity = models.PositiveIntegerField(default=0) tax = models.DecimalField(decimal_places=2, max_digits=10) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Product, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('core:item_details', kwargs={'pk': self.pk }) @property def total_invoice(self): total = (self.price * self.quantity) / self.tax return round(total) class Invoice(models.Model): number = models.AutoField(primary_key=True) description = models.TextField(max_length=300, null=True) date = models.DateField(default=datetime.date.today) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='invoices') created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) product = models.ManyToManyField(Product, related_name='invoices') def __str__(self): return '{}'.format(self.number) def get_absolute_url(self): return reverse('core:invoice_details', kwargs={'pk': self.pk }) How can I implement the features below?? from the main menu of the invoice there is an ADD button for 1 and 2 individually. is_staff is the Manager who can : 1/ CUSTOMER: from ADD button number 1, select the user to be charged. (As soon as selected from that page, the manager is redirected to menu page and the user information selected is populated to menu) 2/ ITEM : Same scenario for choosing item but in this case you can select multiple items from pressing ADD … -
Is there a way to only show a field if specified using django-rest-framework?
I'm using django-rest-framework, https://www.django-rest-framework.org/api-guide/serializers/ Is there a way to show a field only if its specified in the ?field=X param? If I try this: class TopLevelJobSerializer(DynamicFieldsMixin, serializers.ModelSerializer): children_job_statuses = serializers.ReadOnlyField() class Meta: model = TopLevelJob # This inherits from Job, which has id, name fields = ('id', 'name') I get AssertionError: The field 'children_job_statuses' was declared on serializer TopLevelJobSerializer, but has not been included in the 'fields' option. The children_job_statuses is a property that takes a while to load. I only want to call this explicitly by calling /api/top_level_job/?fields=children_job_statuses How can I do this? Do I need a whole new serializer? -
O visual Studio não atualiza minhas mudanças no servidor
Quando modifico alguma coisa no código o Visual Studio não atualiza no servidor. Tenho que fechar e rodar ele novamente. Toda modificação que faço tenho que dá um CTRL C no terminal e python manage.py runserver novamente. Estou fazendo com Django -
Django. Data to xml
Please tell me what I'm doing wrong. I want the data published on the site to be generated on the .xml page. For this, I wrote in **views.py**, the following code: def xml(request): data = Foo.objects.all().filter(is_published=True) context = {'data': data} return render(request, 'export/template.html', context, content_type='application/xhtml+xml') My template.html: <feed> <generation-date>2019-08-01</generation-date> {% if data %} <offer> {% for i in data %} <internal-id="{{ i.id }}"> <type>{{ i.type }}</type> <price>{{ i.price }}</price> </offer> {% endfor %} {% endif %} </feed> The page is displayed without errors, but id, type, price generated empty. Question! The page is generated, but the data does not appear, what am I doing wrong? If I in general do everything wrong. Which way to go to unload site object data. Thank you in advance! -
How to save username in Django model?
I have a simple blog post model and I want to save the author name. My current code only saves the author as an empty value or the default value if it's provided. here is the model class Posts(models.Model): title = models.CharField(max_length=200) body = RichTextUploadingField() created_at = models.DateTimeField(default=datetime.now, blank=True) auther = models.CharField(max_length=200) # 'Post object' title fix def __str__(self): return self.title # 'Postss' plural fix class Meta: verbose_name_plural = "Posts" and here is the view @login_required def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('details', post.pk) else: form = PostForm() form = PostForm() return render(request, 'posts/post_edit.html', {'form': form}) -
Migration error at id in Django Rest Framework
I'm trying to create an api endpoint from my MongoDB database. Everything seems normal, but i keep getting the following error: MigrationError at /mymodel/ id I have no idea where is this coming from, since this is everything the error page says. Here is my model: class mymodel(models.Model): firstfield = models.FloatField() secondfield = models.FloatField() thirdfield = models.CharField(max_length=15) def save(self, *args, using=None, **kwargs): super(mymodel, self).save(*args, using='mydb', **kwargs) Serializers: class mymodelSerializer(serializers.ModelSerializer): class Meta: model = mymodel fields = ('firstfield', 'secondfield', 'thirdfield') def create(self, validated_data): return mymodel.create(**validated_data) My views: class mymodelList(generics.ListCreateAPIView): queryset = mymodel.objects.using('mydb').all() serializer_class = mymodelSerializer class mymodelDetail(generics.RetrieveUpdateDestroyAPIView): queryset = mymodel.objects.using('mydb').all() serializer_class = mymodelSerializer And my urls: path('mymodel/', views.mymodelList.as_view()), path('mymodel/<int:pk>/', views.mymodelDetail.as_view()), -
how to use javascript provided data into a django app?
I use intl-tel-input to make the users choose the country code to add phone numbers but the main problem is the phone numbers aren't saved with the code and that raises some errors and doesn't show the numbers formatted as I want. this is the js script I use to show the widget. <script> var input = document.querySelector("#phone"); window.intlTelInput(input,({})); </script> how can I change this to make the field also saves the country code to the data? -
Cannot assign [...] must be a "CustomUser" instance
I am building a Django application with a form, where a logged-in user, a composer, is able to submit a composition they wrote. For this reason, I'd like the 'composer' field of this composition to be already filled with their name, read-only. I have created a custom user model and linked it via the AUTH_USER_MODEL in the settings. When I create a new composition via the admin interface I have a drop-down list for the composer (showing the available users), and I can successfully create a new composition. While doing the same thing via the front-end, though, I get a 'Cannot assign "'1'": "Composition.composer" must be a "CustomUser" instance.' error. I've also tried with get_user_model() instead of 'settings.AUTH_USER_MODEL' in the Composition model, have tried with all the different ways of gathering the active user, for example putting request.user in a variable 'activeuser' in the context and setting the form manually with value="{{ activeuser }}", all to no avail. myapp/models.py: title = models.CharField(max_length=120) # max_length = required description = models.TextField(blank=True, null=True) composer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) users/models.py: from django.contrib.auth.models import AbstractUser, UserManager class CustomUserManager(UserManager): pass class CustomUser(AbstractUser): pass settings.py: AUTH_USER_MODEL = 'users.CustomUser' myapp/views.py: active_user = request.user form = CompositionForm(request.POST or … -
Update DB data through form in django
I'm trying to add a form on my page that will update a certain field in my DB. This is what the template looks like: {% for row in mydb %} <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form3 %} {{row.firstfield}} {{row.secondfield}} <button name="button3" type="submit" class="btn btn-danger style="background-color: red;">CANCEL</button></td> </form> {% endfor %} The for statements is to display each row of the data in my table in a single line. Near each line, there is a submit button. When this button is clicked, the field secondfield is updated with the value New Value, as you can see in my form. Thi is the part of the view involved: def myview(request, tvticker): row = mydb.objects if request.method == 'POST': ... if 'button3' in request.POST: form3 = form = UpdateForm(request.POST) if form3.is_valid(): profile = form.save(commit=False) profile.save() messages.success(request, f"Success") ... render(request, "main/mytemplate.html", context={'row': row,}) And here is the form: class UpdateForm(forms.ModelForm): SomeField = forms.CharField() class Meta: model = MyModel fields = ("SomeField",) def save(self, commit=True): send = super(UpdateForm, self).save(commit=False) send.secondfield = 'New Value' if commit: send.save() return send My actual code it's not working, is seems to send a POST request but the secondfield value is not updated. For … -
When data post to django api, ConnectionResetError: [Errno 54] occur
I'm recently learning how to use django as backend, and let react redux handle frontend. But when I try to implement login function in frontend, and post data to api, ConnectionResetError: [Errno 54] occurs. I used django's User model to create user, and used rest_framework to create API for login. Then, using react with redux as frontend. When user login, it will trigger reducer to implement a login action with axios.post, but the serverside keeps showing errors. When I just login on API view page, it works fine. So I think the problem is with frontend, but I couldn't figure it out. my API for login class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) my redux action to login export const login = (username, password) => dispatch => { const config = { headers : { "Content-Type": "application/json" } }; const body = { "username" : username, "password" : password } axios.post("/api/auth/login", body, config) .then(res => { dispatch({ type: LOGIN_SUCCESS, payload: res.data }); }).catch(err => { console.log(err); dispatch({ type: LOGIN_FAIL }) }); }; And in my Login.js Component onSubmit = e => { … -
How to allow user to edit only object created by self?
I have a custom user model implemented in my pigeon management app and I want to allow user to edit only pigeon added by self. In backend every user can see only pigeon that are his own based on filter. My problem is that a user can edit all pigeon in the database if they pass to the url an aleatory number that corespond to a pigeon pk in the database. # Pigeon Model class Porumbei(models.Model): id_porumbel = models.AutoField(primary_key=True) data_adaugare = models.DateTimeField(default=timezone.now, null=True, blank=True) crescator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True, help_text="Seria de pe inel. Ex: RO 123456") ... # My url path('porumbei/editare/<int:pk>/', porumbei.views.editareporumbei, name='editareporumbei') # I try somethin like this class Crescatori(admin.ModelAdmin): def has_change_permission(self, request, obj=None): if obj is not None and obj.crescator != request.user: return False return True def has_delete_permission(self, request, obj=None): if obj is not None and obj.crescator != request.user: return False return True I use login required to protect the views but I don't know how to deny a user to edit a pigeon that he don't own. 'To be more coincise, lets suppose that user A has added a pigeon with pk 5 and user B added a pigeon with … -
How to Deny Permission to sub-user to edit only one field and only admin has control to access it...?
Here is My Django Model type_choices = [ ('Yes', 'Yes'), ('no', 'no'), ] verified= models.CharField(max_length=50,default='----',choices=type_choices) name = models.CharField(max_length=50, default='', validators=[MinLengthValidator(4)]) age= models.TextField(max_length=5000, default='') I have a record called Verified and I have to Deny Permission to use the record to all Users and this record should only be used by Admins. Can you help me how to restrict other users to change this record and only readable and admin should have the privilege to change the values of the record?