Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Show message only when form has changed
I have a form and every time the form is updated a message is displayed "Your profile has been updated". This message is shown even if no changes has been performed in the form. How can i prevent the form to show message only when changes has been performed? views.py @login_required(login_url='login') def profilePage(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Your account {} has been updated'.format(request.user.username)) return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'members/profile.html', context) forms.py class ProfileUpdateForm(forms.ModelForm): phone_number = PhoneNumberField(label=False, widget=forms.TextInput(attrs={'placeholder': 'Phone Number'})) image = forms.ImageField(label=False) class Meta: model = Profile fields = ['phone_number', 'image', ] Thank you for help! -
How to include Selenium tests in Github Actions?
I have a basic test like this: When I locally do: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.webdriver.chrome.webdriver import WebDriver from selenium import webdriver class TestKundeSeite(StaticLiveServerTestCase): @classmethod def setUp(cls): cls.browser = webdriver.Chrome(r'crm\tests\chromedriver.exe') @classmethod def tearDownClass(cls): cls.browser.quit() super().tearDownClass() def test_kunde_anlegen(self): self.browser.get('%s%s' % (self.live_server_url, '/crm/kunde_anlegen')) vorname_input = self.browser.find_element_by_name("vorname") vorname_input.send_keys('Max') nachname_input = self.browser.find_element_by_name("nachname") nachname_input.send_keys('Mustermann') email_input = self.browser.find_element_by_name("email") email_input.send_keys('max@hotmail.de') telefon_input = self.browser.find_element_by_name("telefon") telefon_input.send_keys('+4917666994073') web_input = self.browser.find_element_by_name("web") web_input.send_keys('max.de') notiz_input = self.browser.find_element_by_name("notiz") notiz_input.send_keys('Beispielnotiz') self.browser.find_element_by_xpath('//input[@value="Speichern"]').click() when I do: python manage.py test it works fine. But when I push it to Github, I get the following error in Github Actions selenium.common.exceptions.WebDriverException: Message: 'crm\tests\chromedriver.exe' executable needs to be in PATH. How can I overcome this problem? I don't know how to set up a environment for Selenium Tests in Github Actions -
How can I user Django ready LoginView view in my own view?
I mean I want to use LoginView, but inside my own view function. And I want to know that how to write code of that function, that user can Login. -
Django. Url cant find view
I need help with {% url (url to template) %} when i try to open another view i see a NoRewerseMatch error. here is my html file: {% load static %} <head> <link href='{% static "navbar_style.css" %}' rel="stylesheet", type="text/css"> </head> <header> <nav class="headlist"> ---> <a href='{% url "home" %}'><img id = "img1" src="{% static 'logo.png' %}" alt="logo"></a> <ul> <li><a href="#">O nas</a></li> <li><a href="#">Kontakt</a></li> <li><a>Zajęcia</a></li> </ul> </nav> </header> my app(pages)/urls.py from django.contrib import admin from django.urls import path from . import views app_name = 'pages' urlpatterns = [ path('', views.home_view, name='home_view'), path('index/', views.index_view, name='index_view'), ] views.py import... # Create your views here. def home_view(request): listoftexts = Text.objects.order_by('-pub_date') context = { 'listoftexts': listoftexts } return render(request, 'pages/home.html', context) def index_view(request): listoftexts = Text.objects.order_by('-pub_date') context = { 'listoftexts': listoftexts } return render(request, 'pages/index.html', context) -
How to create separate model(table) for Admin User and Normal User in Django
I just want separate table for Normal User and Admin User. -
ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools
Here is the complete error i am getting while uploading on Heroku. ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xjv_7ys0/dbus-python/setup.py'"'"'; file='"'"'/tmp/pip-install-xjv_7ys0/dbus-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-t7juccst/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.6m/dbus-python Check the logs for full command output. -
How can I fix? while (interp->next) ^~ error: command 'gcc' failed with exit status 1
I'm trying to deploy my Django app to Heroku. So I ran into the error like: while (interp->next) ^~ error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-l9i4zubq/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-l9i4zubq/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-vgdty8_x/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.8/psycopg2 Check the logs for full command output. I don't really understand, what the problem is. -
How best to implement the logic for determining the post rank in serializer?
Now I have the serializer like: class PostTopSerializator(serializers.ModelSerializer): id_post = serializers.IntegerField(source='id') comment_count = serializers.SerializerMethodField('get_count_comment') rank = serializers.SerializerMethodField('get_rank') class Meta: model = Movie fields = ['id_post', 'comment_count', 'rank'] def get_count_comment(self, object_id): total_comments = Comment.objects.filter(movie_id=object_id).count() return total_comments def get_rank(self, object_id): return object_id.id the Post with the most comments gets rank 1, second place rank 2, and so on... And I get answer like: [ { "id_movie": 2, "comment_count": 5, "rank": 2 }, { "id_movie": 1, "comment_count": 4, "rank": 1 }, { "id_movie": 3, "comment_count": 4, "rank": 3 } ] how to implement the logic of the methoв: def get_rank(self, object_id): return object_id.id to get the same rank with the same number of comments and the output will be: [ { "id_post": 2, "comment_count": 5, "rank": 1 }, { "id_movie": 1, "comment_count": 4, "rank": 2 }, { "id_post": 3, "comment_count": 4, "rank": 2 } ] -
django HttpResponse Location redirect
I am trying to redirect to another page when http response is True I have added response['Location'] = 'login.html' but it's not working, I am getting a page with True written but not the login page. Can you help me I am new to django. I have written this code if user_obj: response = HttpResponse(True) response['Location'] = 'login.html' return response else: return HttpResponse(False) -
Python Django giving me Forbidden (403) CSRF verification failed. Request aborted
I have added {% csrf_token %} inside all my form tags like this: {% extends 'base.html' %} {% block content %} <form method="post"> {% csrf_token %} #-------------> here it is {% for field in login_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} {field.help_text}} {% endif %} </p> {% endfor %} {% for field in login_form %} {% for error in field.errors %} <p>{{error}}</p> {% endfor %} {% endfor %} {% if login_form.non_field_errors %} <p>{{login_form.non_field_errors}}</p> {% endif %} <input type="submit" value="Login"> </form> {% endblock content %} But when I actually try to login using that form and click the submit button, it should then redirect me to the home page. However, instead it is giving me the below error message: *Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that … -
js saving data entered in forms to models
i'm using the following jquery calendar to add events https://codepen.io/charlie7587/pen/eWLKaZ and i'm wondering how can i add the data entered to my models class Event(models.Model): eventName = models.TextField() NumberofPeopleInvited = models.TextField() class Meta: verbose_name = u'Event' verbose_name_plural = u'Events' -
in Django, multiple select input just returns a single value?
I have a very simple form with a "select" field. For each user in the app it creates an option field, that works fine: <select name="users" id="users" multiple> <option value="{{admin.id}}" selected>{{ admin.username }}</option> <!-- can I delete the admin from this list? --> {% for user in users %} <option value="{{user.id}}">{{ user.username }}</option> {% endfor %} </select> Now when I try to retrieve the values of "users", even if they are all selected I always just get a single value...: if request.method == "POST": title = request.POST["title"] admin = request.user project_users = request.POST["users"] print(project_users) I just get "1" or "2" but not a list? How can I retrieve all of the values from this multiple select? -
Cannot filter a query once slice has been taken django
Follow up onto: AutoField should be present but it's not (django)? related to: "Cannot update a query once a slice has been taken". Best practices? I don't need to filter objects, only order by date and select the most recent one: def get_latest_currency(self): """ Return most up to date value """ up_to_date_currency = Currency.objects.order_by('-currency_value_in_dollars_date')[:1] if not up_to_date_currency.exists(): # No objects yet; fetch currencies update_coins_table() return Currency.objects.order_by('-currency_value_in_dollars_date')[:1] up_to_date_currency is initialized correctly; the last line gives: assert not self.query.is_sliced, \ AssertionError: Cannot filter a query once a slice has been taken. This code represents a view (I want to return a plain JSON object (this is a REST endpoint)). Why is django complaining about a filter when only a slice was used? -
How do i handle an OSError?
I am getting an OSError in my python code as soon as I run the command: "(env) C:\Users\AFFAN QADRI\PROJECT>python manage.py runserver" The error message I get is as follows: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
How to solve autocomplete error "NoReverseMatch at /"? I am making django project can anybody help me
model.py class Mobile(models.Model): mobile_id = models.AutoField mobile_name = models.CharField(max_length=100) views.py def autosuggest(request): print(request.GET) query_original = request.GET.get('term') queryset = Mobile.objects.filter(mobile_name__icontains=query_original) mylist=[] mylist += [x.mobile_name for x in queryset] return JsonResponse(mylist,safe=False) urls.py path("autosuggest/", views.autosuggest, name="Autosuggest"), basic.html <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( "#search" ).autocomplete({ source: '{% url 'autosuggest' %}' }); } ); </script> I am also doing source: '{% url 'my_app_name:autosuggest' %}' in basic.html and in urls.py app_name = 'my_app_name' but it is not work. I am trying to href and another code but not working it show me NoReverseMatch at /. Reverse for 'autosuggest' not found. 'autosuggest' is not a valid view function or pattern name. -
Django Serializer - How to know which parameters was input wrongly
I always put serializers in an try statement that returns false when have invalid format. Like this: Sample model: from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() Sample code: try: testSerializer(data = b).is_valid() except: return HttpResponse("Invalid data type input) Now, I want to return parameters was input incorrectly like this: Parameters: Name, Email was input in wrong type -
AutoField should be present but it's not (django)?
Looking at: https://docs.djangoproject.com/en/3.1/ref/models/instances/#django.db.models.Model.save For convenience, each model has an AutoField named id by default unless you explicitly specify primary_key=True on a field in your model. See the documentation for AutoField for more details. and https://docs.djangoproject.com/en/3.1/topics/db/models/ it seems clear that an object always has an id. I have a model: class Currency(models.Model): currency_name = models.CharField(max_length=100) currency_value_in_dollars = models.FloatField() currency_value_in_dollars_date = models.DateField() def __str__(self): return self.currency_name that I've migrated as: operations = [ migrations.CreateModel( name='Currency', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('currency_name', models.CharField(max_length=100)), ('currency_value_in_dollars', models.FloatField()), ('currency_value_in_dollars_date', models.DateField()), ], ), and when trying to add entries to the db like: def update_coins_table(): if not do_greeting(): print("Gecko crypto board not reachable. Db setup") return crypto_coins_prices = cg.get_price(ids=coins_ids_str, vs_currencies='usd') timezone_now = timezone.now() for coin_key in crypto_coins_prices: coin = Currency(coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now) coin.save() the line: coin = Currency(coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now) gives: unable to get repr for <class 'manage_crypto_currency.models.Transaction'> and coin.save() fails. If I replace the line in question with: coin = Currency(1, coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now) it works. Shouldn't the id auto increment? The last line always overwrites the previous and only one entry gets stored in the end. -
How to authorize my API requests with django google-auth?
I have implemented google-auth in my Django project, using allauth, and it works perfectly. After successful verification, I get some key from this view. from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter { "key": "12b6e1696cdd73ddede1334f683003f63426f423" } At this point how can I authorize my other API requests by this key to identify a user on my server? Or what else I need to do ? How to use this key in my other requests ? -
send a list of items in list in json
im trying to send a list of numbers in a json.. how can i do that? im using django serializer to serialize my db model and output is this : { "id": 9, "original_code": "1144", "factory_code": "4411", "length_m": "2", "width_cm": "2", "g_m2": "5", "shrinkage_length": "12", "shrinkage_width": "15", "group": 1, "color": [ 1, 2 ] } i want to use seralizer for my input too...but the issue is seralizer accept 1 value(and when i print the result value is saved in a list) for color but when im trying to add another one i receive error... can you hellp me please? -
Django | Generate Total Price from Price per Item and Amount?
im new to Django and im playing a bit around. So i want to create a Model Field that is dynamicly showing the total price generated from the Amount and Item Price given by the User. Is there a way to do this easy? I would love to find out how that works. -
my application running both django and react when i call api cors error is occure like here
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/accounts/update. (Reason: CORS request did not succeed). XHRGEThttp://localhost:8000/api/accounts/update my django settings is CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] and installed 'corsheaders' also bt i getting this error please help -
Profile page is showing error under postlist href since pk number is increasing?
in blog page, i have made profile pages link for every user. there is also a view for userlist where users linked to their own profile page. here is my blog/models.py: class Post(models.Model): title = models.CharField(max_length=255) body=RichTextField(blank=True,null=True) image=models.FileField(upload_to="mediaphoto",validators=[validate_file_size]) topImage=ImageSpecField(source='image',processors=[ResizeToFill(750,300)],format='PNG',options={'quality':60}) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) category=models.ForeignKey(Category,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) blog/views.py: class CustomContentMixin: def get_context_data(self, **kwargs): context = super(CustomContentMixin, self).get_context_data(**kwargs) context['user_list']= Profile.objects.all() context['category_list']=Category.objects.all() return context class BlogappListView(CustomContentMixin,ListView): model = Category,Profile template_name = 'home.html' context_object_name='post_list' queryset=Post.objects.all() paginate_by=7 class BlogappUpdateView(CustomContentMixin,UpdateView,LoginRequiredMixin,UserPassesTestMixin): model=Post template_name='post_edit.html' fields=('title','body','image','category') login_url='login' def test_func(self): obj = self.get_object() return obj.author == self.request.user class BlogappDetailView(DetailView,LoginRequiredMixin,FormMixin): model=Post template_name='post_detail.html' login_url='login' form_class=CommentForm def get_success_url(self): return reverse_lazy('post_detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(BlogappDetailView, self).get_context_data(**kwargs) context['comments']=Comment.objects.filter(post=self.object) context['comment_form']=CommentForm() context['user_list']= Profile.objects.all() context['category_list']=Category.objects.all() return context def post(self, request, *args, **kwargs): self.object = self.get_object() comment_form = self.get_form() if comment_form.is_valid(): return self.form_valid(comment_form) else: return self.form_invalid(comment_form) def form_valid(self, comment_form): comment_form.instance.post = self.object comment_form.instance.author=self.request.user comment_form.save() return super().form_valid(comment_form) class BlogappDeleteView(CustomContentMixin,DeleteView,LoginRequiredMixin,UserPassesTestMixin): model=Post template_name='post_delete.html' success_url=reverse_lazy('home') login_url='login' def test_func(self): obj = self.get_object() return obj.author == self.request.user class BlogappCreateView(CustomContentMixin,CreateView,LoginRequiredMixin): model=Post template_name='post_new.html' login_url='login' fields=('title','body','image','category') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) acounts/models.py: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) name=models.CharField(max_length=30, blank=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birthdate = models.DateField(null=True, blank=True) def … -
how do I post a foreign key by some other field rather than primary key in django rest framework
I am developing a pet management api and this is what I post to the body when assigning a day of the week to a pet : { "day": "Sunday", "pet_name": 2 <-- how to add pet name (rather than the primary key)(this is a foreign key) } How do I pass in the pet name which is the foreign key's field rather than the primary key field. -
updating an user's object in django
i have a problem in updating an exsited object in my models ,when i update and change the user object its gonna save and everything is looked ok but i guess its just save ,because when i change the user and i want to login ,beside of login view this user dosnt authenticated and dosnt login. here my code def profile_edit(request): user = request.user profile = request.user.profile context = { 'user': user } if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') user.profile.address = request.POST.get('address') user.profile.phone = request.POST.get('phone') user.set_password('password') user.username = username user.save() user.profile.save() authenticate(user) context = { 'profile': profile } return render(request, 'helpdesk/profile.html', context) return render(request, 'helpdesk/profile_edit.html', context) and login view def login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) profile = request.user.profile context = { 'profile': profile } return render(request, 'helpdesk/user_desk.html', context) else: context = { 'username': username, 'error': 'user not find!' } else: context = {} return render(request, 'helpdesk/login.html', context) -
Django calendar clickable days
I'm implementing an events calendar and i'm trying to make clickable days that automatically fill in day field in my models is there a way to pass selected day to the day field in models.py or is there any widget that i can use instead of this one? Here is my models.py models.py class Event(models.Model): day = models.DateField() start_time = models.TimeField(u'Starting time', help_text=u'Starting time') end_time = models.TimeField(u'Final time', help_text=u'Final time') notes = models.TextField(u'Textual Notes', help_text=u'Textual Notes', blank=True, null=True) class Meta: verbose_name = u'Scheduling' verbose_name_plural = u'Scheduling' def check_overlap(self, fixed_start, fixed_end, new_start, new_end): overlap = False if new_start == fixed_end or new_end == fixed_start: #edge case overlap = False elif (new_start >= fixed_start and new_start <= fixed_end) or (new_end >= fixed_start and new_end <= fixed_end): #innner limits overlap = True elif new_start <= fixed_start and new_end >= fixed_end: #outter limits overlap = True return overlap def get_absolute_url(self): url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.id]) return u'<a href="%s">%s</a>' % (url, str(self.start_time)) def clean(self): if self.end_time <= self.start_time: raise ValidationError('Ending hour must be after the starting hour') events = Event.objects.filter(day=self.day) if events.exists(): for event in events: if self.check_overlap(event.start_time, event.end_time, self.start_time, self.end_time): raise ValidationError( 'There is an overlap with another event: ' + str(event.day) …