Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF when generating cookie sessionid
I am creating /auth/ page on my Django Rest Framework site. And I can not save session id. Have i create this cookie or its creating automatically? My auth view: class AuthView(APIView): permission_classes = (permissions.AllowAny,) renderer_classes = [TemplateHTMLRenderer] @csrf_exempt def get(self, request): return render(request, 'login.html', {}) @csrf_exempt def post(self, request): serializer = AuthFormSerializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.data username = data.get('username') password = data.get('password') if username is None or password is None: return Response({'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST, template_name='login.html') user = authenticate(username=username, password=password) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND, template_name='login.html') self.token, _ = Token.objects.get_or_create(user=user) user_token = Token.objects.get(user_id = user.pk) if (datetime.now() - user_token.created.replace(tzinfo=None)).days > 10: Token.objects.update(user_id=user.pk, key=Token.generate_key(user.pk), created = datetime.now()) context = {'token': self.token.key} # return Response(, status=HTTP_201_CREATED, template_name='') return HttpResponse(json.dumps(context), content_type="application/json") -
How to extend field in UserCreationForm in django?
I have been trying to add a phone number field in UserCreationForm so that on registration a user gives its phone number but unfortunately phone number is not storing. it accepts the Phone number on the registration page but it doesn't show the phone number on the webpage. I think it is not storing. forms.py class myCreateForm(UserCreationForm): ph= forms.CharField(max_length=400, required=True, label='Phone') class Meta: model = User fields = ['first_name', 'last_name' ,'username', 'email', 'password1', 'password2','ph'] def save(self, commit=True): user = super(myCreateForm, self).save(commit=False) user.ph = self.cleaned_data["ph"] if commit: user.save() return user views.py def register(request): form = myCreateForm() if request.method == "POST": form = myCreateForm(request.POST) if form.is_valid(): form.save() return redirect('loginPage') return render(request , 'register.html', {'form' : form}) template {%for i in user%} Hi {{i.first_name}}<br> Username : {{i.username}}<br> E-Mail : {{i.email}}<br> Phone : {{i.ph}}<br> {%endfor%} but on my webpage, it shows everything except phone number. Please Help Me Out -
How to keep Celery running in Django (drf) + Redis + WSGI (EC2)
I don't think its a very new question. I just could not find the right answer. I am trying to use Celery for background tasks while implementing a backend with the Django Rest Framework. I have a Redis server. Celery is working as expected with celery worker -A my_project --loglevel=info However, it does not work if I sop this command. How do I keep that running? I have found a blog with supervisor. I just want to know what is the standard (as well as easier) to do this. -
Formset not applying required=True
I use a formset, made of several forms, where each form contains a ModelChoiceField. However, while I wrote required=True for this field, I am able to post data although I do not select anything in it (when looking at the HTML source code, I can indeed check that required is not included in the select tag). Moreover, formset.is_valid() returns True contrary to what I expected. So far, I have managed to solve this by adding 'required' : 'required' in attrs (see below), but I guess it is not the usual way to achieve this. Here are my forms.py: class InitialForm(forms.Form): group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True, label="Poule", widget=forms.Select(attrs={'class': 'select'})) nb_rounds = forms.IntegerField(min_value=1, max_value=5, required=True, label="Nombre de manches", initial=1, widget=forms.NumberInput(attrs={'class':'input', 'style': 'width:5ch'})) nb_teams = forms.IntegerField(min_value=2, max_value=5, required=True, label="Nombre d'équipes", initial=2, widget=forms.NumberInput(attrs={'class': 'input', 'style': 'width:5ch'})) class FinalForm(forms.Form): def __init__(self, *args, **kwargs): group = kwargs.pop('group') nb_rounds = kwargs.pop('nb_rounds') super(FinalForm, self).__init__(*args, **kwargs) self.fields['teams'] = forms.ModelChoiceField(queryset=Team.objects.filter(group=group), required=True, label="Equipe", widget=forms.Select(attrs={'class': 'select', 'required': 'required'})) for i in range(nb_rounds): self.fields['score_%i' % i] = forms.IntegerField(min_value=0, max_value=50, required=True, label="Score", initial=0, widget=forms.NumberInput(attrs={'class':'input', 'style': 'width:5ch'})) and views.py def initial_new_game(request): # GET request if request.method == 'GET': form = InitialForm() return render(request, 'initial_form.html', {'form': form}) # POST request else: form = InitialForm(request.POST) if form.is_valid(): request.session['group_id'] … -
Django: How do I upload an image to a folder named after the article slug
I defined two models Article, Article_photos. Photos present in each article is stored in the relevant Article_photos model. I intend to store multiple photos per article in this way. I want each photo to be uploaded to a folder by naming the folder in this manner: {slug}_images. This is Article model: class Article(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='Author') article_title = models.TextField() article_content = models.TextField() slug = models.SlugField(max_length=30, blank=True) ... def save(self, *args, **kwargs): self.slug = slugify(self.article_title) super(Article, self).save(*args, **kwargs) And the Article_photos model to store one or more photos: class Article_photo(models.Model): article = models.ForeignKey('Article', on_delete=models.CASCADE) photo = models.ImageField(upload_to='{}_images'.format(article.slug)) Now, when i'm running makemigrations, it's returning this error: AttributeError: 'ForeignKey' object has no attribute 'slug'. How do rename the folder in the pattern I want? -
Use mongoDB with django 3.0
As I said in the title I want to integrate mongoDB next to my Postgres Database in a Django3.0 project. I used to use djongo* but it seems it's not compatible with the latest version of Django. What do you think is the best connector to use mongoDB in a Django project ? *https://github.com/nesdis/djongo -
Django Serve Other Files and Default Route
If I should split this up into 2 questions I will but I have 2 major questions here. First Question How can I serve a directory as the default in Django? I build a django/react application. Got it all set up with uWSGI. Static files for both react and django working (using whitenoise for multiple static directories). But files like /favicon.ico and /manifest.json in the index.html built from react return a 404 error because they don't exist. How can I get django to attempt to serve files in the same directory as index.html if everything else fails? Currently I serve index.html by doing the following in Django: In myproject/urls.py: urlpatterns = [ path('', index, name='index'), ...other-stuff ] In myproject/views.py index = never_cache(TemplateView.as_view(template_name='myproject/index.html')) So what about the other files that need to be served? Am I supposed to be defining them all manually, or is there a way to do it properly? Second Question How can I get django to redirect all unknown urls to / Since the react part of the project uses react-router, it changes the url in the SPA. So if I go to /options in the app, it works, but if I were to … -
how to remove these usercreation forms instruction in django
class Driver_SignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): fields = ("username", "email", "password1", "password2") model = User help_texts = { 'username': None, 'email': None, 'password1': None, 'password2': None, } this is the code i already use the help text none but not working properly here is image of that -
POST request return 405 on auth (nginx angular)
i'm using django and angular with nginx. I get 405 not allowed when i try to post to /auth/. my nginx conf: server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /home/dev/projet-name/frontend/my-app/dist/tryangular; include /etc/nginx/default.d/*.conf; location / { try_files $uri $uri/ /index.html; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } location ~ ^/(api|admin)/ { include uwsgi_params; uwsgi_pass SERV_IP:3031; } } Djnago is on the same server. I don't even know where i messed up -
Disable CSRF validation on Wagtail Page
I'm trying to do a curl POST request on a wagtail page. Unfortunately I hit the CSRF protection. I tried to disabled CSRF on this specific type of page using the @csrf_exempt decorator, without success. Here is my pseudo code (one of many attemps): @method_decorator(csrf_exempt, name='serve') class NewsletterPage(MedorPage): class Meta: verbose_name = _("newsletter page") Seems like the csrf verifition is done even before the serve method is called. Any idea? thanks -
Counting the many-to-many value in filter
I am trying to do like this my class is here class TweetJson(models.Model): authors = models.ManyToManyField(Station) and filter MyText.objects.filter(Q(authors__count__gte=1)) However it returns. Related Field got invalid lookup: count is there any way to count the number of many-to-many objects? -
The value in __init__ doesn't returns correct value?
I have a model in django: class Game(models.Model): gaming = models.BooleanField(default=False) def __init__(self, *args, **kwargs): super(Game, self).__init__(*args, **kwargs) self.old_gaming = self.gaming Now, when I print the value of self.old_gaming it comes out to be True instead of False while working from an application. Whereas, while I work on django-admin it shows False. Why is it showing two different values? -
Django - How to get the object attribute before updating in Update class based view?
I'm learning Django and I'm struggling with the Class Based View of Django. I would like to access the object attributes before the update in order to show the user what was the previous attributes. Here my class view : class GroupUpdateView(LoginRequiredMixin, UpdateView): model = GroupName fields = ['name', 'description'] template_name = 'dashboard/groups/group_update_form.html' group_name_before_editing ="" #I wanted to write model.name here #Overrive def form_valid(self, form): return super().form_valid(form) def get_success_url(self): messages.success(self.request, "The group %s was updated successfully" % ( self.group_name_before_editing)) return reverse_lazy('dashboard:group-update', args=(self.object.pk,)) In get_success_url(), I would like to show the user the previous name of the group that has been updated. I tried also with the get_context_data() but was not able to obtain the result. Could you help please ? How to get the current model attributes ? -
Django search : query multiple table, join them then return the queryset
I'm building a search for my product price tracking app and there're 2 models products and scans class products(models.Model): product_id = models.IntegerField(primary_key=True) product_name = models.CharField(max_length=100) product_link = models.CharField(max_length=255) image_link = models.CharField(max_length=100) store_name = models.CharField(max_length=100) class Meta: verbose_name_plural = "products" def __str__(self): return str(self.product_name) class scans(models.Model): scan_id = models.IntegerField(primary_key=True) prod_id = models.IntegerField(models.ForeignKey("scrape.Model", on_delete=models.CASCADE)) price = models.IntegerField() scanned_time = models.DateTimeField(default=timezone.now) class Meta: verbose_name_plural = "scans" def __repr__(self): return str(self.prod_id) the search is supposed to take a name(string) input and query for a store name in the same table and query for price which is in another table and return the query set with the product_name, store_name and price. I've tried this class searchResults(ListView): model = 'products', 'scans' template_name = 'result.html' # let query = GET request from form (in home.html) def get_queryset(self): queryset = [] rawquery = self.request.GET.get('q') queries = rawquery.split(" ") for q in queries: prodresults = products.objects.filter( Q(product_name__icontains=q) ).distinct() for prodresult in prodresults: prod_id = products.objects.get(product_name=prodresult).product_id prod_price = scans.objects.get(prod_id=prod_id).price for result in prodresults: #joins results toegther queryset.append(result) queryset.append(prod_price) return list(set(queryset)) The code broke at prod_price = scans.objects.get(prod_id=prod_id).price with scans matching query does not exist. -
django-autocomplete-light add parameter to query url (in version 3.3)
I'm using django-autocomplete-light in a django admin change_form.html page, however I need to change dynamically the GET parameters of the URL depending on another field. I have already tried to replicate this answer django-autocomplete-light add parameter to query url, but failed since I am using version 3 Tried this way: $("#id_city").change(function(){ url = '{% url "custom-pop-autocomplete" %}'; $('#id_p').attr('data-autocomplete-light-url', url + `?city=${$(this).val()}`); $('#id_p').trigger('autocompleteLightInitialize'); }); This way: $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(function() { $(this).initialize }); and this way: $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(function() { window.__dal__initialize(this); }); None of them working to reinitialize django-autocomplete-light. I just need to change the URL. -
Django DeprecationWarning Use of .. or absolute path
I am getting a lot of these warnings in production but not on devstack which is making me curious to know about this warning and how to get rid of this. Apparently there is no information which imports is causing the issue. I am looking for any tools, documentation that explains this Deprecation warning when this will raise an exception in the future and steps to get rid of this warning. thank you! [__init__.py:1566] - /edx/app/edxapp/venvs/edxapp/lib/python3.5/site-packages/pkg_resources/__init__.py:1158: DeprecationWarning: Use of .. or absolute path in a resource path is not allowed and will raise exceptions in a future release. -
Insert Data From HTML to Django Template
I want to save data from HTML template into database Model. I want to override this toplaner_name, toplaner_avatar, toplaner_price everytime I submit the Form. The img and span tags are dynamically changing by JS template <form method='POST'> {% csrf_token %} <div class="player-on-map toplaner"> <img class='img-on-map' src="{% static 'images/ago/img1.png' %}" alt="portrait-on-map"> <span class="nickname">Szygenda</span> <span>Price: 1500</span> </div> <button type='submit'>SAVE TEAM</button> </form> models.py class Team(models.Model): toplaner_name = models.CharField(max_length=30, default='Ibo') toplaner_avatar = models.ImageField(default='avatar.png') toplaner_price = models.IntegerField() JS toplaners.forEach(toplaner => toplaner.querySelector('.btn').addEventListener('click', function(){ toplaner_on_map.innerHTML = toplaner.innerHTML; toplaner_on_map.querySelectorAll('.btn, .position, .player-price').forEach(item => item.classList.add('hide')) })) -
How to support django data migration in a plugin design
I'm trying to implement a plugin design pattern in a django app to dynamically extend the app functionality. Everything looks routine: I'm gonna have a parent abstract class/interface and each plugin implements the required methods and registers itself to the plugin manager... But, each plugin may need it's specific database models to work with. I have no idea how to implement it through plugin pattern. Any workaround to provide django db migrations dynamically? -
How to export a model with images to an excel in Django?
I have a model which it contains some data and a ImageField in my Django project and I want to export them to an excel with images. How can I do that? -
How do you compare today's date with the date provided by Django using JavaScript/JQuery?
The whole problem is to compare the date extracted from the database and passed to the input field in the template with today's date generated by jquery. Unfortunately when I tried print el console return me "undefined value" What I created so far: <input type="date" class="date" hidden data-book="{{ book.slug }}" value="{{ book.date|date:"Y-m-d" }}"> $( document ).ready(function() { let endDt = new Date(); $(".date").each(function () { let el = $(this).attr('data-book').val; if( (new Date(startDt).getTime() < new Date(endDt).getTime())) { // Rest of code here } }); }); -
how can i edit instance of the Project class in the Django shell after i created
i created an entry in my projects table and saved it to the database with django shell but i want to customize my entry after i created what should i do ? >>> p1 = Project( ... title='My FirstProject', ... description='Another web development project.', ... technology='Flask', ... image='img/project1.png' ... ) >>> p1.save() >>> p2 = Project( ... title='My Second Project', ... description='A final development project.', ... technology='Django', ... image='img/project2.png' ... ) >>> p2.save() -
multiple aspect filter in abay sdk
response = api.execute('findItemsAdvanced', {'keywords':'Macbook', }, 'aspectFilter':[{'aspectName': 'Series','aspectValueName': 'MacBook Air'}, {'aspectName': 'Processor', 'aspectValueName': 'AMD A10'}] }) Now i am working in ebaysdk . i am facing the problem with multiple aspect filter. Is there any solution for multiple aspect filter.if aspect filter is single it is working fine but multiple are not -
DRF: testing POST method using Client()
I have a class that accepts the dictionary list - data = [{}, {}] . If I send data via Postman, everything will work but the problem with testing POST class method. The error is FAIL: test_vendor_from_csv_create (vendors.tests.VendorCsvCreateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/y700/projects/solution/apps/vendors/tests.py", line 128, in test_vendor_from_csv_create self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200 views.py class CsvToDatabase(APIView): def post(self, request, format=None): r_data = request.data for data in r_data: if data['nda'] == '': data['nda'] = None ... #some logic serializer = VendorsCsvSerializer(data=data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) test.py class VendorCsvCreateTest(APITestCase): #API def test_vendor_from_csv_create(self): url = reverse('csv_vendor_create') response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) I assume the problem is format='json'. If this is the case, how do I transfer the data in the right format? If the reason is different, can you give me a solution, please! -
Redirect to item page after deleteView in class based views
I have an invoice page with each invoice (factuur) has items in it (relation invoice-items with ForeignKey). When I delete one of the items with the class based deleteView I want to redirect back to the specific invoice id with the remaining items in it. urls.py: path('factuur/<factuur_id>', views.facturen_detail_view, name='facturen_detail_view'), path('delete/<int:pk>', views.FactuurItemDeleteView.as_view(), name='delete_factuurItem'), views.py: class FactuurItemDeleteView(BSModalDeleteView): model = FactuurItems template_name = 'delete_fitem.html' success_message = 'Succes: factuur item is verwijderd.' success_url = reverse_lazy('facturen_detail_view') So what I want is redirect it to /factuur/factuur_id after deletion (where I was at the moment of clicking the delete button). But how do I redirect as I need to know invoice id (factuur_id) in the first place. I don't know how to do this with the class based views method. When success_url is as above then it tries to redirect to the factuur_id with the deleted item_id what is not the wanted situation. -
page not found error while passing paarmeter through url in view django
I am new to python django. I am facing an issue while passing parameter to view through URL in django. code: views.py from django.shortcuts import render from django.http import HttpResponse def hello(request): text = "HEllo" return HttpResponse(text) def viewArticle(request, articleId): text = "HEllo : %d"%articleId return HttpResponse(text) urls.py from django.conf.urls import url from django.urls import path,include from myapp import views urlpatterns = [ path('hello/',views.hello,name='hello'), path('article/(\d +)/',views.viewArticle,name='article'), ] image: