Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to make a chat app without django-channrls
Hello how can I make a chat app without django-channels. I want to do it with something like socketio. I found in Google a module named django-socketio. Should I do it with this? Please write me the code to do this or write a link of a tutorial. -
Django REST Framework: Strange behaviour in unit tests
Good evening, at the moment I'm creating the unit tests for a pretty basic model in combination with the authentification of a json web token. Also I'm using a custom user model. Notice: a few lines of code will be cut off for a better overview - there unimportant for my question. models.py: USER = get_user_model() class MainTask(models.Model): id = models.BigAutoField(primary_key=True, unique=True) title = models.CharField(max_length=50, null=False, blank=False, unique=True) active = models.BooleanField(default=True) slug = models.SlugField(null=False, blank=False, unique=True) created_by = models.ForeignKey(USER, null=False, blank=False, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py: class MainTaskListCreateView(ListCreateAPIView): queryset = MainTask.objects.all() serializer_class = MainTaskSerializer pagination_class = PageNumberPagination urls.py: urlpatterns = [ path('maintask/', MainTaskListCreateView.as_view(), name='maintask-list'), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), ] settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', 'rest_framework.permissions.IsAuthenticated', ], } test_views.py: USER = get_user_model() class MainTaskTest(APITestCase): url_verification = reverse('token_obtain_pair') url_maintasks = reverse('maintask-list') def setUp(self): self.email = 'johndoe@email.com' self.password = 'johndoepassword' self.data = { 'email': self.email, 'password': self.password } USER.objects.create_user(email=self.email, password=self.password) def test_auth_user(self): response = self.client.post(self.url_verification, self.data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue('access' in response.data) self.assertTrue('refresh' in response.data) def test_get_obj(self): response_verification = self.client.post(self.url_verification, self.data, format='json') token = response_verification.data['access'] self.client.credentials(HTTP_AUTHORIZATION=f"JWT {token}") response = self.client.get(self.url_maintasks, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertNotEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) self.assertNotEqual(response.status_code, status.HTTP_403_FORBIDDEN) Problem: When running the test above, I get an error 403, the … -
TwilloRestfullException on inbound call in django_two_factor_auth
I am using django_two_factor_auth version 1.13.1 with python 3.6, and when I try to get OTP via phone call it returns TwilloRestfullExeption on URL. HTTP 400 error: Unable to create a record: Url is not a valid URL: http://localhost:8000/twilio/inbound/two_factor/206039/?locale=en in my URLS.py I have added the URLs paths url('', include(tf_urls)), url('', include(tf_twilio_urls)), one more thing when I try to hit that URL via postman or web browser I got 200 success response <?xml version="1.0" encoding="UTF-8" ?> <Response> <Say language="en">Your token is 1. 7. 3. 8. 4. 7. Repeat: 1. 7. 3. 8. 4. 7. Good bye.</Say> </Response> -
wagtail api : my pages dont appear in /api/cms/pages/
I ve configured my wagtail to use the api and to serve the pages on /api/cms/pages/ endpoint. But I only have the default page being served on this endpoint : "meta": { "total_count": 1 }, "items": [ { "id": 2, "meta": { "type": "wagtailcore.Page", "detail_url": "http://localhost/api/cms/pages/2/", "html_url": "http://localhost/", "slug": "home", "first_published_at": null }, "title": "Welcome to your new Wagtail site!" } ] } I have created a few BlogPages and PostPages but they dont appear there. How can i configure my django/wagtail files so they appear? The documentation here : https://docs.wagtail.org/en/stable/advanced_topics/api/v2/usage.html is not very detailed... Here is my models.py : import urllib.parse from django.http.response import JsonResponse, HttpResponseRedirect from django.conf import settings from django.db import models from django.utils.module_loading import import_string from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from modelcluster.fields import ParentalKey from modelcluster.tags import ClusterTaggableManager from taggit.models import Tag as TaggitTag from taggit.models import TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel, PageChooserPanel, StreamFieldPanel, ) from wagtail.core.models import Page from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.snippets.edit_handlers import SnippetChooserPanel from wagtail.snippets.models import register_snippet from wagtail.core.fields import StreamField from wagtail.contrib.routable_page.models import RoutablePageMixin, route from wagtail.search import index from wagtail_headless_preview.models import HeadlessPreviewMixin from .blocks import BodyBlock from wagtail.api import APIField from .fields import TagField, CategoryField, … -
{detail: Unsupported media type "text/plain; charset=utf-8" in request.}
I am using Flutter and Django and have this error when try to call the backend Back end error : {detail: Unsupported media type "text/plain; charset=utf-8" in request.} Flutter code : Future<void> addAlbum(Album album) async { print('5'); final url = Uri.parse('http://127.0.0.1:8000/list-create/'); try { print('6'); final response = await http.post(url, headers: { 'Authorization': 'Token dc7e96ed776bc44d013b44fdfe560a616c64646f', }, body: json.encode({ 'title': album.title, 'cover': album.cover, // => this is an int 'photos_number': album.photos_number, // => this is an int })); print('6 ed'); final responseData = json.decode(response.body); print(responseData.toString()); final newAlbum = Album( title: album.title, cover: album.cover, photos_number: album.photos_number, ); print('6 edddgg'); _items.add(newAlbum); print('6 f'); notifyListeners(); } catch (error) { print('7'); print(error); throw error; } } } -
Django API call from extern Website via AJAX Javascript
i am working for the first time with Django Framework. A service provider is using django i can see the data only with an active Cookie on their API Docs. We received now an API Token to call for the data on the framework. I am trying to call the data with the Token via AJAX but i receive everytime the same console log "401 (Unauthorized)". $.ajax({ type: 'POST', headers: { 'X-CSRFTOKEN': "XXXXXXXXXXXXXXX", 'Content-Type': 'application/json' }, url: 'www.service-provider.url/api/...', success: function () { console.log("ok"); }, error: function () { console.log("error"); } }); Sorry i'm a beginner at this point and have no idea where to begin with. I've searched for solution on the inet but couldn't find anything that would work. -
Have Integerated the ckeditor in django model but when saving the data from ckeditor django admin panel it is not saving to database , showing blank
I am using RichText Field from ckeditor.fields import RichTextField class Section(BaseContent): image = ImageWithThumbsField(upload_to='static/%Y/%m/%d', sizes=((90,120),(180,240),(360,480)),blank=True, null=True ) # image = ImageWithThumbsField(upload_to='static/%Y/%m/%d',blank=True, null=True ) description = RichTextField("Section description. Appears in section home page", blank=True, null=True) url4SEO = models.SlugField("SEO friendly url, use only aplhabets and hyphen", max_length=60) summary = models.CharField("Byline/ Summary", max_length=300, blank=True, null=True) css = models.CharField("Section specific CSS", max_length=300, blank=True, null=True) allowContent = models.BooleanField("Should this section allow any content(such as News and Event)?", default=True) parent = models.ForeignKey('self', blank=True, null=True,on_delete=models.DO_NOTHING) home_disp = models.BooleanField(default = False) sub_description=RichTextField("Section sub description. Appears in section portfolio page", blank=True, null=True) sub_image=ImageWithThumbsField(upload_to='static/%Y/%m/%d', sizes=((90,120),(180,240),(360,480)),blank=True, null=True ) # sub_image=ImageWithThumbsField(upload_to='static/%Y/%m/%d',blank=True, null=True ) is_active = models.BooleanField() -
Django Template request.GET.value don't work
I need to set selected="selected" for a select field. <form action="{% url 'books:book_detail' book.pk %}" method="get"> {% csrf_token %} <select name="country"> {% for shop_country in shop_countries_list %} {% if request.GET.country == shop_country.pk %} <option value="{{ shop_country.pk }}" selected="selected">{{ shop_country.name }}</option> {% else %} <option value="{{ shop_country.pk }}">{{ shop_country.name }}</option> {% endif %} {% endfor %} </select> <button class="button" type="submit">Search</button> </form> But it's not working. I think that request.GET.country inside the if statement is null or empty. But if I to put request.GET.country in some other place of my code like this: {{ request.GET.country }} - it give the correct value. So the question is why it doesn't give any value inside the if statement? -
Registering Django objects with child objects
I have two tables named product and variant. I am building an offer creation module. While creating the offer, I want to pull the products from the product and variant table and save them to the offer product table, but I am having problems with the checkboxes. model.py from django.db import models from firma.models import company class variant(models.Model): name = models.CharField('Varyant Adı',max_length=200) price = models.IntegerField('Varyant Fiyat') stok = models.IntegerField('Varyant Stok') company = models.ForeignKey(company,on_delete=models.CASCADE) image = models.FileField(upload_to="variant",default="") def __str__(self): return f"{self.name}" class product(models.Model): name = models.CharField('Ürün Adı',max_length=200) price = models.IntegerField('Ürün Fiyat') stok = models.IntegerField('Ürün Stok') variant = models.ManyToManyField(variant,blank=True) company = models.ForeignKey(company,on_delete=models.CASCADE) image = models.FileField(upload_to="product",default="") def __str__(self): return f"{self.name}" model.py class offerProductInfo(models.Model): offerProductName = models.CharField('Ürün Adı',max_length=200) offerProductPrice = models.IntegerField('Ürün Fiyat') offerProductStok = models.IntegerField('Ürün Stok') offerProductVariant = models.ManyToManyField(offerVariantInfo,blank=True) offerProductCompany = models.ForeignKey(company,on_delete=models.CASCADE) offerProductImage = models.ImageField(upload_to="product") def __str__(self): return f"{self.offerProductName}" view.py def teklifsave(request): if not request.user.is_authenticated: return redirect('login') if request.method == 'POST': offerVariantId = request.POST.getlist('offerVariantId') offerProduct = request.POST.getlist("offerProducts") count = -1 for fproduct in offerProduct: print(fproduct) count += 1 h = variant.objects.get(id=offerVariantId[count]) c = h.product_set.all() print(c) s = offerVariantInfo( offerVariantName = h.name, offerVariantPrice = h.price, offerVariantStok = h.stok, offerVariantCompany = h.company ) s.save() z = product.objects.get(id=fproduct) c = offerProductInfo( offerProductName = z.name, offerProductPrice = z.price, … -
Django ValueError: field admin.LogEntry.user was declared with a lazy reference to 'app.user', but app 'app' doesn't provide model 'user'
I have a similar problem to this post but its only answer didn't help: ❯ python manage.py makemigrations No changes detected Because when I execute python manage.py migrate I get the following traceback: ❯ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, portfolio, sessions Traceback (most recent call last): File "C:\Users\user\Projects\personal_website\src\packages\pweb_django\manage.py", line 23, in <module> main() File "C:\Users\user\Projects\personal_website\src\packages\pweb_django\manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\commands\migrate.py", line 236, in handle pre_migrate_apps = pre_migrate_state.apps File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\db\migrations\state.py", line 544, in apps return StateApps(self.real_apps, self.models) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\db\migrations\state.py", line 615, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'portfolio.user', but app 'portfolio' doesn't provide model 'user'. Yet, when I check the file portfolio\models.py it clearly provides the 'user'-model: class User(AbstractUser): """Dummy class in order to mimic a standard Auth-user. Docs: https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project """ pass In the related … -
On Raw HTML, website looks as I intend it. But on Django, there is some blank space created during the for loop
<div id="Project" class="bg-white fnt-white brdr project-div "> <div class="float-left image-for-project-container brdr"> <img src="{% static './Images/manworking.webp' %}" alt="manworking" height="630px"> </div> {% for project in project_details %} <div class=" project-container inline-block "> <h2 class="text-center fnt-black head-portfolio"> {{project.project_name}} </h2> <br> <br> <p class="margin-auto txt-portfolio roboto hover-orange fnt-black"> {{project.project_details}} </p> <br> <a href="#" class="buttons read-more fnt-black">Read More</a> </div> </div> Issue: The project container when receiving dynamic entries from Django model, creates multiple project containers as executed by the forloop. However, as evident from the image attached, as each project container is created, it is creating an unwanted upward indentation or margin successively. What am I doing wrong? This is the HTML code. I do not think there is any requirement for my CSS stylesheet as when I view the HTML file without Django, it's absolutely alright. I have also attached an image to show the space that is being created. In case the Imgur is not being shown here is the link (https://i.stack.imgur.com/EnUUG.png). -
How do I update data in a linked django rest model?
How do I update data in a linked django rest model Here is my json { "doc_type": 1, "warehouse": 4, "date": "2022-06-09", "number": 980, "contragent": 2, "comment": "testcom;mgment", "items": [ { "product": 7, "buy_price": "168.00", "sell_price": "500.00", "quantity": 17 }, { "product": 8, "buy_price": "168.00", "sell_price": "500.00", "quantity": 17 } ] } I can't change the data in the "items" dictionary If I submit only one "product" element, will the other one be deleted? And if, for example, three, will it be added? this is what I have at the moment, records are created without problems, but I can only update the "ConsignmentNote" model #serialisers.py class ConsignmentNoteSerializer(serializers.ModelSerializer): creator = serializers.HiddenField(default=serializers.CurrentUserDefault()) doc_type = serializers.IntegerField(read_only=True) # contragent_detail = ContragentSerializer(source='contragent', read_only=True) items = ConsignmentItemSerializer(many=True) class Meta: model = ConsignmentNote fields = ['doc_type', "warehouse", 'date', 'number', 'contragent', 'comment', 'creator', 'items'] read_only_fields = ['id' ] def create(self, validated_data): items = validated_data.pop('items') note = ConsignmentNote.objects.create(**validated_data, doc_type = 1) for item in items: product = item.pop('product') item = ConsignmentItem.objects.create(consignmentnote=note, product=product ,**item) return note def update(self, instance, validated_data): instance.date = validated_data.pop('date', instance.date) instance.comment = validated_data.pop('comment', instance.comment) return instance -
Compare entirely two different models in Django
I have been working in Django template. I have been stuck here since quite some time now. {% for i in LOOP %} {% if i == {{SECOND VARIABLE}} %} //Do Something {% endif %} {% endfor %} LOOP and second variable are entirely different. Is there something we can do? Is there some alternate solution -
Django,MSSQL server query and pagination
This is a sample of my MSSQL server table Employeetable emp_id name status EMP001 A STATUS-A EMP001 A STATUS-B EMP002 B STATUS-C EMP001 A STATUS-D EMP002 B STATUS-D EMP003 C STATUS-C Now in my app front end page there is a table in which each employee is listed once in the table and expanding each employee will show their every available status For Example: EMPID NAME EMP001 A ---STATUS-A #After expanding the EMP001 row it shows all the status of EMP001 ---STATUS-B ---STATUS-D EMP002 B EMP003 C So how can we use pagination in this consider there are about 200K records and about 100K distinct employees -
How do I test if my django is connecting to my cloud proxy auth mysql site?
I am receiving this error: django.db.utils.ProgrammingError: (1146, "Table 'xpotoolsdb.xpotoolshome_site' doesn't exist") in pycharm on mac os and windows 10. My coworkers are not and they are able to run a local development environment. How would I go about troubleshooting this error? It seems as if my local dev env is not finding a table in the mysql database but I don't think it's actually connecting at all since my coworkers aren't receiving the same error. -
Forms django -> is_valid
i'm currently developping an application on django and when i send a post request from a form, is_valid method return false. my forms.py : from django import forms class formadduser(forms.Form): mail = forms.CharField(label='Mail', max_length=40) # imput_username = forms.CharField(input='input_username', max_length=100) prenom = forms.CharField(label='Prénom', max_length=25) # input_password = forms.CharField(input='input_pathword', max_length=100) nom = forms.CharField(label = 'Nom', max_length=25) -
should I use drf APIView's alongside with django Views in a production project?
I am just learning djangorestframework and my question is: "should I use APIView's alongside with Views?" my friend told me that I should have an api app and for some parts you should only use normal django Views and other parts related to admins the APView. Now I'm a bit confused what should my project structure look like for exmple in an ecommerce project? Thanks for your help! -
Django Validation Check More than two negative list value will give validation error
i have this data , so basically i have to check if i have one list of negative value and one list of positive value and then if i add another list of negative values will rasie validation error. how i can implement that.I am working on django . django /models.py a=[-8,-9] & b=[8,9] & c=[-7,-12] def clean(self): if (self.a <0 and self.b >0).exists , then adding another negative list will raise validation error -
Request swagger with Django view
i'm trying to request swagger of django app from django view. To clarify what I mean, this is an example: @action(methods=['GET'], detail=False, permission_classes=[AllowAny]) def get_swagger(self, request, *args, **kwargs): try: be_url = "http://localhost:8000/?format=openapi" r = requests.get(be_url) except Exception as e: return Response('data': str(e)) return Response('data': r.json()) But when I request this endpoint response goes very long and then fails with a 404. -
Django smtp sendmail is not working for sending mail
I wrote this on settings.py DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = '*********' forms.py from django import forms from django.conf import settings from django.core.mail import send_mail class Emailform(forms.Form): name = forms.CharField(max_length=120) email = forms.EmailField() inquiry = forms.CharField(max_length=70) message = forms.CharField(widget=forms.Textarea) def get_info(self): cd = super().clean() name = cd.get('name').strip() from_mail = cd.get('email') subject = cd.get('inquiry') msg = f'{name} with email {from_mail} said:' msg += f'\n"{subject}"\n\n' msg += cd.get('message') return subject, msg def send(self): subject, msg = self.get_info() send_mail( subject=subject, message=msg, from_email=settings.EMAIL_HOST_USER, fail_silently=False ) views.py from django.views.generic import FormView, TemplateView from .forms import Emailform from django.urls import reverse_lazy from django.shortcuts import redirect class EmailView(FormView): template_name = 'index.html' form_class = Emailform success_url = reverse_lazy('mailapp:success') def form_valid(self, request): if request.method == 'POST': form = Emailform(request.POST) if form.is_valid(): form.send() return redirect('mailapp:success') else: form = Emailform() class EmailSuccessView(TemplateView): template_name= 'success.html' My code is running successfully, but I'm not receiving the mail. I even tried to edit the send function, but it's not working even after that. I'm just confused here. Can anyone tell me why am I getting this problem? My python version is 3.10 and Django version is 4.0.5. Thank you in … -
Django production multiple post request
I have a question regarding the multiple handling of django. I have read the answers to this question How does Django handle multiple requests?. I wrote a django application and it is deployed which takes POST request and do some string splitting in the background and returns the results on the side. My problem would be that if two users sent two POST request (from two different clients), then the process is slowed down dramatically and I only see one process in my Apache server. I am not sure whether Django handles just a request at a time and I could not distribute the process properly. Is a asynchronical restructuring necessary? Thanks -
How do I add packages to an existing docker container using pipenv
I currently have a Django app running in a docker container and I want to install additional packages to the container without rebuilding the entire container. I've tried bringing up the container using: docker-compose up then docker-compose exec web pipenv install "package_name_here" what happens is the package installs but I lose it the moment I shut down the container. How do I persist the installation even after shutting down the container without also rebuilding the entire container? -
django and mypy with apps in a subfolder
We have a Django project with the following setup: We have our apps in an apps folder. We added all those apps to the python path at settings.py level. We then can refer and import these apps like so: from apps.booking.models import Booking # or from booking.models import Booking Now, we want to use mypy for type checking purposes. The issue is that mypy does not recognize the import from booking.models import Booking and complains about missing stubs for this module. This make the typing very unreliable and not very useful as Booking is then typed as Any. It works fine with an import as follow however from apps.booking.models import Booking Is there a way to make mypy understand the path without the prefix apps. ? I tried to use mypy_path = $MYPY_CONFIG_FILE_DIR/apps in mypy.ini but without any success... -
Send POST from JS to Django
I'm trying to send POST with some veriables to DJANGo Send from JS: function sendStatistic(csrftoken, song_id, answer) { fetch('request/', { method: 'POST', headers: { 'X-CSRFToken': csrftoken, 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: { 'Song-Id': song_id, 'Answer': answer ,}, }); } And try to capture 'Song-Id' and 'Answer' in Django but request.POST.get('Answer') returns None what am I doing wrong? -
File sharing system
I need a file sharing system, precisely videos, to create a movie site, educational or something like that. To be a good option, it must meet the following criteria, or almost all of them: Videos accessible only on my website Easy implementation Good price The django project is complete, I just need links to embed for video playback class Episode(models.Model): movie = models.ForeignKey("Movie", related_name="episodes", on_delete=models.CASCADE) title = models.CharField(max_length=100) video = models.URLField() # This embedded link def __str__(self): return f'{self.movie.title} - {self.title}'