Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF cookie error after Django 3.2 update (DRF with token authentication)
I was looking to update my app backend from Django 3.1.14 (working fine but no longer supported) to a newer version (I tried both 3.2 and 4.0), but after updating I started getting a CSRF cookie error. Forbidden (CSRF cookie not set.): /api-token-auth/ Does anybody by any chance know what's changed in Django in regard to CSRF, and how to avoid the errors? I was under the impression that CSRF is not enforced when using Django Rest Framework with token authentication. I tried anyway to remove the 'django.middleware.csrf.CsrfViewMiddleware' middleware, to add @csrf_exempt to all the views, deleted all existing tokens and logged out of Django admin, but to no avail. My DRF configuration in settings.py is as follows: INSTALLED_APPS = [ 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } -
Using Django-Taggit in Django Rest Framework 3.13.1 with Django 4.0.2 with Error "Invalid json list" in Serializing Tags Model Attribute
Older solutions uses django-taggit-serializer which is now been deprecated and doesn't work with the version I have. I have already done what the documentation says regarding the integration with DRF. However, I am getting this error: b'{"tags":["Invalid json list. A tag list submitted in string form must be valid json."]}' image error in drf browsable api Here is my code viewset.py class AnnouncementViewSet(viewsets.ModelViewSet): """Announcement ViewSet.""" queryset = Announcement.objects.all() serializer_class = AnnouncementSerializer lookup_field = "slug" permission_classes = [IsAdminUser, IsAuthorOrReadOnly] def get_permissions(self): """Return permissions.""" if self.action in ["create", "update", "partial_update", "destroy"]: self.permission_classes = [IsAdminUser] else: self.permission_classes = [IsAuthorOrReadOnly] return super().get_permissions() models.py class Announcement(models.Model): """Announcement model.""" created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) title = models.CharField(_("title"), max_length=255, unique=True) content = models.TextField(_("content")) is_featured = models.BooleanField(default=False) thumbnail = models.ImageField( upload_to="announcement/thumbnail", default="announcement/thumbnail/default.jpg" ) tags = TaggableManager(_("tags")) slug = models.SlugField(_("Slug"), max_length=255, unique=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args, **kwargs) serializers.py class AnnouncementSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Announcement exclude = ["slug"] extra_kwargs = { "url": {"view_name": "api:announcement-detail", "lookup_field": "slug"} } What I have tried so far: tags = "my-tag" tags = ["tag1", "tag2"] I even wrote a test: tests.py def test_announcement_create_url( self, api_client: Client, admin_user ): api_client.force_login(admin_user) response = api_client.post( … -
Django check if many-to-many relationship exists
I have a kind of social network in Django where people can send direct messages. Within all of those messages, I have a conversation field to show who the messages are between so that I can group the messages by person when displaying them to the user. I'm trying to figure out how I can search for if a conversation exists. In the print statements below in the view, I get back: <QuerySet [<Conversation: Sarah and Stephen>, <Conversation: Sarah and James>]> <QuerySet [<User: Sarah>, <User: Stephen>]> <QuerySet [<User: Sarah>, <User: James>]> In the view below, the sender is 'Sarah' and the receiver is 'James', so I'm trying to figure out how I can search for if a conversation between them already exists (through filter or something) by matching them with the kinds of QuerySet lists above so that if so, I can use that conversation and if not, I can create the conversation. I've tried many things but keep getting stuck. I'm pretty new to many-to-many relationships. The view def writemessage(request, id): profile = Profile.objects.get(id=id) context = { 'profile': profile, } conversations = Conversation.objects.all() print(conversations) for each in conversations: print(each.participants.all()) if request.method == 'POST': sender = request.user receiver = profile.user … -
Search functionality works but not getting any results (django project)
I am currently working on my Django app and the search functionality is working but I am not getting a response on the site ( at pets.html is where the search form is located ). The URL looks right when a submit request is being sent and the keywords are visible in the URL. No errors in the console. Any help is greatly appreciated Here is the link to the repository: https://github.com/Amanuel763/Athenawebsite -
Django: dates not send properly in values tag
:) I send in context dates that want to use in chart labels, but every time when I use it in tag I get with "&#x" every begining and ending If I use it normally in HTML it work... -
Do I need to create both a web application and an api for it
I have this thought about restful api's. I use django for web development and i really want to know weather i should build both a django web application or a django restapi web application or both of them because i find it pretty confusing. -
DRF SocialLoginVeiw Custom? or Create New View?
class KAKAOLogin(SocialLoginView): adapter_class = KakaoOAuth2Adapter client_class = OAuth2Client serializer_class = SocialLoginSerializer def get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs) now i using Django allauth SocialLoginView. when Signin my app, i used Username (not email). but when i using SocialLoginView, enter username as "real name" or "user" to DB. In this case, I would like to know if it is better to create a new Login View and use it, or if it can be modified and used in the above code. what should i do? -
No reverse match. Ideas how to fix?
Can anyone figure out why I'm getting a no reverse match error here: urls.py: urlpatterns = [ path('', views.ReservationsFormView.as_view(), name='reservations'), path('edit/<slug:pk>/', EditReservationView.as_view(), name="edit_reservation"), path('reservation_complete/', ReservationCompleteView.as_view(), name="reservation_complete"), path('reservations_account/', ReservationAccountView.as_view(), name="reservations_account"), path('delete/<slug:pk>/', DeleteReservationView.as_view(), name="delete_reservation"), ] It's only happening, so far, on my edit/delete paths (the one's with the slug:pk) views.py: class ReservationsFormView(CreateView): model = Reservations template_name = "reservations/reservations.html" form_class = ReservationForm success_url = "reservation_complete/" def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) class EditReservationView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): form_class = ReservationForm template_name = 'reservations/edit_reservation.html' success_url = "/reservations_account/" model = Reservations def test_func(self): return self.request.user == self.get_object().user class ReservationCompleteView(CreateView): template_name = "reservations/reservation_complete.html" success_url = "/reservation_complete/" form_class = ReservationForm model = Reservations class ReservationAccountView(ListView): template_name = "reservations/reservations_account.html" model = Reservations def get_context_data(self, **kwargs): context = { 'reservations': self.model.objects.filter(user=self.request.user), } return context class DeleteReservationView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): """ A view to delete an reservation """ model = Reservations success_url = "/reservations_account/" def test_func(self): return self.request.user == self.get_object().user Corresponding Html is: <button href="{% url 'edit_reservation' reservation.id %}" type="button" class="btn btn-dark">Edit</a> <button href="{% url 'delete_reservation' reservation.id %}" type="button" class="btn btn-dark">Delete</a> Error Message: NoReverseMatch: Reverse for 'delete_reservation' with no arguments not found. 1 pattern(s) tried: ['reservations/delete/(?P[-a-zA-Z0-9_]+)/$'] Really hoping it's something simple. Any help is appreciated. If you need to see more … -
How to catch an empty query exception with Django
I'm after an elegant and efficient approach. I am doing a query to a model that has a chance to return an empty queryset and if that happens I must do a query with other parameters that will work for sure. It would be really nice if I could put the query inside a simple try except but it doesn't catch like so. What's holding me back from using .exists() is that it feels like I'm doing the query to the database two times. One to check the existence and the other to really get the object. -
Function failure after closing SSH in Django
I have written the below function in views.py to check whether the given mobile number is authorized or not @api_view(['POST']) def authorize_subscriber(request): if request.method == 'POST': data=request.POST str = "\"" authorization_data=ast.literal_eval(str.join(list(data.keys()))) try : sub = Subscription.objects.get(accountid=authorization_data["mobile"]) status_message={"message":"success","data": { "mobile": sub.accountid, "calling_code": "+91", "subscription_start_date": sub.subscriptionstartdate, "subscription_end_date": sub.subscriptionenddate } } error=status.HTTP_200_OK except : status_message={'message': 'Unauthorized Request'} error=status.HTTP_401_UNAUTHORIZED #print(status_message) return JsonResponse(data=status_message,status=error) This function is working fine when I use ssh to server and run Django server but it is failing when I exit ssh. If I exit the ssh except for this function all other functions are working fine. In request POST, I am getting the data as shown in the below format <QueryDict: {'{"mobile":"9160208253"}': ['']}> Below is my script which is used to run the Django server. user -k -n tcp 8085 cd /home/absott/.myplatform gunicorn --timeout 600 --bind 0.0.0.0:8085 myplatform.wsgi & Can anyone help me to fix this issue? -
Best way to reuse code from an old data migration in a new data migration
A few months ago, I wrote a custom data migration that created some model objects. I wrote a function inside the migration file, create_data, and then for the migration operation, ran it using RunPython operations = [ migrations.RunPython(create_data) ] Now, we have another object we need to be automatically populated by migrations. I'd like to reuse my create_data function, but in a new migration. Problem is, I don't know if I can import it properly, or if importing from a previous migration is a bad idea. create_data = __import__('projects.project.migrations.0012_auto_20210331_2126').create_data This doesn't work, but anyways I think there are issues importing from files that start with numbers that make this weird. The other idea I have is to copy paste this function into one of my normal django apps where reusable code lives, then I could import it as usual and use in future migrations without issue as well. The downside is that the code is still copy pasted once. How should I reuse my old code from this older migration in a new migration? Is there a nice way to import it, or should I just copy paste it to a better place and never put logic in migration files … -
How to modify all databases when overriding DiscoverRunner setup_databases with parallel
I'm running the tests with --parallel and want to add some object to every database that is created (for each process). currently, I have a CustomTestRunner which inherit from DiscoverRunner. In that class, I'm overriding setup_databases method. after calling super().setup_databases(), I'm making a change in the db (like Users.objects.create(....)) The changes occur only in one of the databases, But I want that change to be in all of them. How can I achieve that? My Custom Test Runner -
add help text for OneToOneField
I want to add a help_text to a field in my admin create for a model. I already tried what is suggested here. models.py: class Product(models.Model): name = ... ean = models.OneToOneField(EANCode, on_delete = models.CASCADE, help_text = "from model, not visible ...") forms.py: class ProductAdminForm(forms.ModelForm): class Meta: model = Product fields = '__all__' help_texts = {"name": "this is visible", "ean": "this is not visible"} So I can add a helptext to a CharField but not to a OneToOneField. Why? -
'“1” is not a valid UUID.' Django
Getting this error when i try to delete a reservation from a user account on my restuarant booking app. Tried a few things to no avail so if anyone can help I'd greatly apprecaite it. Code is as follows: class Reservations(models.Model): """ reservation form categories and attributes """ user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) name = models.CharField(max_length=50) phone_number = models.CharField(validators=[phoneNumberRegex], max_length=16, unique=True) email = models.EmailField() date = models.DateField() time = models.CharField(choices=time_options, default="12pm", max_length=10) number_of_party = models.IntegerField(choices=party_size, default=1) reservation_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Not sure where the 1 is even coming from in this instance. If you need to see more code ask and i'll edit the post. Thanks in advance. -
Problem with different divs size and infinity scroll
django/bootstrap/infinity scroll(https://infinite-scroll.com) I want to add infinity scroll to my news page. Queryset with 2 types of news, big(col-lg-8) and small(col-lg-4). Now I have problems with blocks (see example picture). How to make pagination page added to the previous page row? Example <div class="container"> <div class="article-feed"> <div class="row iscroll"> {% for art in all %} {% if art.banner_page %} <div class="col-lg-8 mb-2 mt-2"> <img class="card-img-top" src="{{art.banner.url}}" > </div> {% else %} div class="col-lg-4 mb-2 mt-2 "> <img class="card-img-top" src="{{art.banner.url}}" > </div> {% endif %}{% endfor %} <p class="pagination"> <a class="pagination__next" href="?page={{ page_obj.next_page_number }}"> </a></p> <script src="{% static "js/infinite-scroll.pkgd.min.js" %}"></script> <script> $('.article-feed').infiniteScroll({ path: '.pagination__next', append: '.iscroll', }); </script> -
how can I prepare and put Time series forecasting graph in html of Django project interactive by chartjs?
I want to make an interactive website where users can upload or input their data and get forecasting analysis result based on python Time series graphs. Is there a free python or javascript module for handling python graphs in django project? I pointed some modules like Chartjs but how can I show Time series analysis in something like chartjs? -
NOT NULL constraint failed: spring_post.publisher_id
I created a class base create view.When i try to submite the post model create view. it will return NOT NULL constraint failed: spring_post.publisher_id how can i set the publisher the get the current logged in user and set it to the post piblisher field. im a beginner this is the publisher field in my post model publisher=models.ForeignKey(User,on_delete=models.PROTECT) #and this is my views class PostCreateView(LoginRequiredMixin,CreateView): model=Post fields=['title','description'] redirect_field_name="login" -
Adding Data from Bootstrap Cards as Django Objects Using Checkboxes
This is kind of a complicated question, but: I am using Django. User enters data on one template and then using logic in my view and an API call, the next page is rendered which displays multiple bootstrap cards, each containing data from that API call present in that first view. On top of each bootstrap card holding the data is a checkbox. I would like to have the user be able to check/uncheck any bootstrap card to add the data from those cards as a new object (NewNFT from my models.py). In an attempt to make it less complicated, I will just share my html, which shows how each card is formatted with the text box/data from the API call and then I will also share my model for the object that is being created. Is anyone able to explain how to add each of these 'cards' (really data from each card) as a new object for my model? I can't figure out the view.py logic to make that happen. For some reason it's not letting me display, but of course there would be a form around the card data as well as a submit button. And the data … -
Does Zappa support Djangos recently added async functionality?
I'm starting to learn Django's new native async support: https://docs.djangoproject.com/en/4.0/topics/async/ Is it supported by Zappa? I've tried creating a basic async view but when I deploy it using Zappa the view just runs in normal sync mode. I'm aware that Zappa has it's own async functionality (wish I knew about it earlier), but I'd prefer to use the Django async. -
Many to Many table of MYSQL database in django
I connected my Django project to an existing MySQL database. Migration worked well and I can see the new Django-generated tables in the MySQL database. I have some many-to-many relationship tables in the MySQL database, without primary keys, since it is not necessary for MySQL. The Django documentation specifically states that every model needs a primary key and that Django might auto-generate a primary key column. When running inspectdb, I don't see that Django added anything to my database. An example table "countries" the columns: country_id and country_name many-to-many table "country_neighbors" the columns: country_id and neighbor_country_id(which is a country_id in the countries table) Question: Can I just use my database as is and use the inspectdb-generated foreign keys in the many-to-many model as I did when I only worked directly with the mysql database? many thanks! -
Django render not working and stays on the same page
import json from django.shortcuts import render, redirect from django.views import View from django.core.mail import send_mail from .models import MenuItem, Category, OrderModel class Index(View): def get(self, request, *args, **kwargs): return render(request, 'customer/index.html') class About(View): def get(self, request, *args, **kwargs): return render(request, 'customer/about.html') class Order(View): def get(self, request, *args, **kwargs): # get every item from each category appetizers = MenuItem.objects.filter( category__name__contains='Appetizer') entres = MenuItem.objects.filter(category__name__contains='Entre') desserts = MenuItem.objects.filter(category__name__contains='Dessert') drinks = MenuItem.objects.filter(category__name__contains='Drink') # pass into context context = { 'appetizers': appetizers, 'entres': entres, 'desserts': desserts, 'drinks': drinks, } # render the template return render(request, 'customer/order.html', context) def post(self, request, *args, **kwargs): name = request.POST.get('name') email = request.POST.get('email') street = request.POST.get('street') city = request.POST.get('city') state = request.POST.get('state') zip_code = request.POST.get('zip') order_items = { 'items': [] } items = request.POST.getlist('items[]') for item in items: menu_item = MenuItem.objects.get(pk__contains=int(item)) item_data = { 'id': menu_item.pk, 'name': menu_item.name, 'price': menu_item.price } order_items['items'].append(item_data) price = 0 item_ids = [] for item in order_items['items']: price += item['price'] item_ids.append(item['id']) order = OrderModel.objects.create( price=price, name=name, email=email, street=street, city=city, state=state, zip_code=zip_code ) order.items.add(*item_ids) # After everything is done, send confirmation email to the user body = ('Thank you for your order! Your food is being made and will be delivered soon!\n' f'Your total: {price}\n' 'Thank … -
Django Q object is adding extra - IS NOT NULL
for the below raw query, I want to build Django ORM query Select * from employee WHERE (address_id is not null OR address_id<>'*') AND (xyz_id is null OR xyz_id='*') AND (abc_id is null OR abc_id='*') So I have build ORM query as below data = Employee.objects.filter(~Q(employe_id="23") | Q(employe_id__isnull=False), Q(xyz_id__isnull=False) | Q(xyz_id='*'), Q(abc_id__isnull=True) | Q(abc_id=‘*’)) and when i print the query, it is showing as below SELECT "employee"."id", "employee"."xyz_id", "employee"."abc_id" FROM "employee" WHERE ((NOT ("employee"."address_id" = 23 AND "employee"."address_id" IS NOT NULL) OR "employee"."address_id" IS NOT NULL) AND ("employee"."xyz_id" IS NOT NULL OR "employee"."xyz_id" = *) AND ("employee"."abc_id" IS NULL OR "employee"."abc_id" = *)) my question is why Q object in Django is adding bolded line in above generated query ? which is not solving for above raw sql criteria. i am using Django 2.2 version Kindly advise -
Issues with NGINX / SSL Certificate when running docker-compose with NGINX, Django & Acme companion
I have a problem that's been bugging me for a couple of days, and I'm not sure if it's a pure NGINX issue or have something to do with SSL certificates, so I'll explain the issue I'm facing in hope of that someone can help me weed out where the issue is coming from. I'm running the following docker-compose file consisting of a Django application, a Nginx-proxy and a container using let's-encrypt to generate a SSL certificate, I have got the inspiration for it from the docs on the Docker image for the let's-encrypt container and a tutorial: https://github.com/nginx-proxy/acme-companion/blob/main/docs/Docker-Compose.md https://testdriven.io/blog/django-lets-encrypt/ docker-compose.yml version: '2' services: web: container_name: web restart: always labels: - "com.centurylinklabs.watchtower.enable=true" image: index.docker.io/username/myreponame:latest command: gunicorn myreponame.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/dockeruser/web/staticfiles - media_volume:/home/dockeruser/web/mediafiles expose: - 8000 env_file: - ./.env.prod logging: driver: "json-file" options: max-size: "100m" network_mode: bridge nginx-proxy: image: nginxproxy/nginx-proxy container_name: nginx-proxy ports: - "80:80" - "443:443" volumes: - conf:/etc/nginx/conf.d - vhost:/etc/nginx/vhost.d - html:/usr/share/nginx/html - certs:/etc/nginx/certs:ro - /var/run/docker.sock:/tmp/docker.sock:ro network_mode: bridge acme-companion: image: nginxproxy/acme-companion container_name: nginx-proxy-acme volumes_from: - nginx-proxy volumes: - certs:/etc/nginx/certs:rw - acme:/etc/acme.sh - /var/run/docker.sock:/var/run/docker.sock:ro network_mode: bridge volumes: conf: vhost: html: certs: acme: static_volume: media_volume: If I run the containers I can access the website via the browser and … -
How to get the full url in reverse function
I appreciate help with the following issue. In models.py (I use the app django-payments) class Payment(BasePayment): def get_failure_url(self): return "http://127.0.0.1:8000/collaborate/donate/payment-failure" return reverse('payment_failure') def get_success_url(self): return "http://127.0.0.1:8000/collaborate/donate/payment-success" In urls.py urlpatterns = [ path("donate/payment-failure/",views.payment_failure, name='payment_failure'), In views.py def payment_failure(request): template_name = 'collaborate/payment_failure.html' return render(request, template_name) In models.py, I override the method "get_failure_url" in order to redirect to the error url, but the sample code (django-payments) has a hard-coded url (http://127.0.0.1:8000/collaborate/donate/payment-failure). In my case, I want to use other expression calling a View name 'payment_failure', but I don't know how to obtain the full url. I have tried using "return reverse('payment_failure')", but it doesn't work, because the path is "https://sis-t.redsys.es:25443/", and not the url of my web. thanks, -
how can i schedule expo notifications from python
native expo for application and python[django] for backend , i have created an app and successfully sent notification from python to my app [i am using expo notifications for sending notifications] but i want to schedule them , its possible in react native directly but i want to do it from python for some other purpose. can someone help me with this this is my code for generating notification @api_view(['GET']) def sendNotification(request): token = StoreToken.objects.all().last() print(token) if token == None: return Response({'detail':'something went wrong'}, status=status.HTTP_400_BAD_REQUEST) message = { 'to' : token.token, 'title' : 'hello', 'body' : 'this is body' } return r.post('https://exp.host/--/api/v2/push/send', json = message)