Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Actually I added a mysql database to the django and I'm getting this error
System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions Running migrations: No migrations to apply. -
How to improve performance of query in Google datastore via Djangae?
I would like to know how to improve query performance in a table with around 100000 records, using Google's datastore and Djangae. Thank you in advance. Model class Species(models.Model): id = models.AutoField(primary_key=True) scientific_name = models.CharField(max_length=64, null=False, blank=False, unique=True, db_index=True) common_name_en = models.CharField(max_length=64, null=False, blank=False) common_name_es = models.CharField(max_length=64, null=False, blank=False) common_name_fr = models.CharField(max_length=64, null=False, blank=False) image_url = models.CharField(max_length=128, null=False, blank=False) def __unicode__(self): return "{self.scientific_name}".format(**locals()) class Meta: verbose_name_plural = "species" Admin class SpeciesAdmin(admin.ModelAdmin): admin_caching_enabled = True list_per_page = 10 fields = ['scientific_name'] list_display = ['scientific_name'] readonly_fields = ( 'scientific_name', ) After trying the following queries from the shell the response takes too long. Query 1 result = Species.objects.order_by('scientific_name')[0:1].get() Query 2 result = Species.objects.all()[:5].get() Query breakdown from Django Admin -
ERROR Error: jQuery requires a window with a document using angular 2
So everything was going fine and our angular app was running smoothly but then, all of the sudden, we decided to use angular universal. I face couple of errors but eventually made it to work. but now, I am getting this error. ERROR Error: jQuery requires a window with a document I have looked at every possible solution here. All of them really don't provide solution regarding angular 2. I am using npm run build:ssr && npm run serve:ssr command to run my node server. And for anyone who is interested to know which tutorial I followed here is the link: https://medium.com/@MarkPieszak/angular-universal-server-side-rendering-deep-dive-dc442a6be7b7 One important thing is that my home page and my 404 pages are loading just fine. Other routes won't load. No error in console. I am using Djnago REST API as a backend. Any help will be of huge help. Thank you. -
object appears in multiple graph cliques
I have a piece of code that supposed to find cliques of nodes, while nodes are ids of django model objects: import networkx as nx final_groups = [] graph = nx.Graph() for img_test in Same_Img_Test.objects.filter(id__in=test_ids, is_same=1): graph.add_edge(img_test.product_1.id, img_test.product_2.id) for x in nx.find_cliques(graph): final_groups.append(x) print x I get this result: [1293856L, 909760L] [1293856L, 909730L] [1293856L, 909797L] [1293856L, 909767L] [1293856L, 909741L] my question id: how same id (1293856L) can occur in multiple cliques? isn't the result supposed to be something like: [1293856L, 909760L, 909730L, 909797L, 909767L, 909741L] what am I doing wrong? -
ManytoMany fields data
I encountered a problem with my ManyToMany. I can add objects inside but I have troubles understanding the request to call the data. This is my model.py: class Parcours(models.Model): articleList = models.ManyToManyField('Article') author = models.CharField(max_length=250,blank=True) class Article(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) fileItem = models.OneToOneField('FileItem', on_delete=models.CASCADE, null=True) title = models.CharField(max_length=100) author = models.CharField(max_length=100) thumbnail = models.ImageField(upload_to='media/static') category = models.ForeignKey('Category',on_delete=models.CASCADE, null=True, blank=True) #TODO date = models.DateTimeField(default=timezone.now, verbose_name="Date de Parution") slug = models.SlugField(max_length=100) content = models.TextField() adress = models.CharField(max_length=250,blank=True) autorisation = models.BooleanField(default=True,verbose_name="Autorisation des commentaires") Each ManyToMany needs an author. What am I doing wrong? Thanks in advance. -
fetch request using Django rest framework doesn't return data
I've set up a Django app with a React/Redux frontend. I've set up a simple API using Django Rest Framework and have confirmed that with the Django development server running, a cURL request returns valid data from the mySQL database. However when I use a fetch request in the web page, no data is returned to the JavaScript code. Here's my JavaScript: let headers = { 'Content-Type': 'application/json' }; return fetch('/api/lists/', { headers, }) .then(res => { console.log('res ', res); }); And here's what's printed in the console when it runs: Response {type: "basic", url: "http://127.0.0.1:8000/api/lists/", redirected: false, status: 200, ok: true, …} body : (...) bodyUsed : false headers : Headers {} ok : true redirected : false status : 200 statusText : "OK" type : "basic" url : "http://127.0.0.1:8000/api/lists/" __proto__ : Response Obviously not the same response! I have selected the request the browser sends in the Network tab and chosen Copy > Copy as cURL: curl 'http://127.0.0.1:8000/api/lists/' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' -H 'Content-Type: application/json' -H 'Accept: */*' -H 'Referer: http://127.0.0.1:8000/' -H 'Connection: keep-alive' --compressed If I paste this into a terminal … -
Django Oscar - In checkout process payment details process is getting skipped
I have small eCommerce project in django-oscar. In my checkout process payment details process is getting skipped, i have not yet forked the oscar checkout app still getting this error. my console responce [17/Dec/2018 18:37:57] "GET /checkout/payment-method/ HTTP/1.1" 302 0 Why is it redirect to payment preview page? Any solution on it or suggestion -
How can I customize field in template? (forms.IntegerField)
I have a trouble. I have form: from django import forms class CartAddProductForm(forms.Form): quantity = forms.IntegerField(min_value=1, initial=1) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) How I can customize this field in template? I try do it by widget, but just broken form, lol. Help me pls, I feel me retarded. -
Django [Errno 13] Permission denied: '/var/www/media/'
I can not add comment to this post https://stackoverflow.com/a/21797786/6143954. It was the correct answer before it was edited. In this answer, the line “sudo chmod -R 750 / var / www /” is replaced by “sudo chmod -R 760 / var / www /”. . Specifically, this solution is not suitable for Django. The answer should not be changed after it has been marked as the right solution. That was the correct answer before correcting the original post. The GOOD solution would be: sudo groupadd varwwwusers sudo adduser www-data varwwwusers sudo chgrp -R varwwwusers /var/www/ sudo chmod -R 770 /var/www/ -
Django - TimeField difference
I would like to compare two time fields to get the difference in hours and minutes. class Labor(models.Model): id = models.AutoField(primary_key=True) start_hour = models.TimeField(null=True) end_hour = models.TimeField(null=True) def hours(self): return self.end_hour - self.start_hour But, if try to use the hours method, django throws this exception: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' I would like that the difference returns me something like this: 10:00 ~ 11:30 = 1:30 11:30 ~ 11:45 = 0:15 How could I do that? -
Django elasticsearch 'User' object is not iterable
i ciurrently implementing elasicsearch into my DJango Aapp but each time i try to create a new post object i get the following error TypeError at /post/new/ 'User' object is not iterable this is what my documents.py looks like (index of Post model): from django_elasticsearch_dsl import DocType, Index, fields from elasticsearch_dsl import analyzer from myproject.models import Post, Category from myproject_Accounts.models import User posts = Index('posts') html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @posts.doc_type class PostDocument(DocType): author = fields.ObjectField(properties={ 'user': fields.TextField(analyzer=html_strip), 'pk': fields.IntegerField(), }) category = fields.NestedField(properties={ 'title': fields.TextField(analyzer=html_strip), 'description': fields.TextField(analyzer=html_strip), 'pk': fields.IntegerField(), }) class Meta: model = Post fields = [ 'id', 'title', 'content', 'tag', 'published_date', ] related_models = [User, Category] def get_queryset(self): """Not mandatory but to improve performance we can select related in one sql request""" return super(PostDocument, self).get_queryset().select_related( 'author', 'category' ) def get_instances_from_related(self, related_instance): """If related_models is set, define how to retrieve the Post instance(s) from the related model. The related_models option should be used with caution because it can lead in the index updating a lot of items. """ if isinstance(related_instance, User): return related_instance.post_set.all() elif isinstance(related_instance, Category): return related_instance.post models.py (usermodel): class User(AbstractBaseUser): user = models.CharField(verbose_name='username',max_length=20,unique=True) bio = models.TextField(blank=True, null=True, max_length=2500,) avatar = … -
python django-fcm incompatibility issue
I am trying to install django-fcm but while installing pip install -r req.txt It gives error django-fcm 0.1.1 has requirement django>=1.9, but you'll have django 1.8.4 which is incompatible. django-fcm 0.1.1 has requirement djangorestframework>=3.3.2, but you'll have djangorestframework 3.2.4 which is incompatible. same setup with requirement file I run before week but now it says incompatible. When I tried to run server it gives error from matplotlib.nxutils import points_inside_poly ImportError: No module named nxutils -
How to document parameters with @api_view on DRF with Django REST Swagger 2.0
Is there a way to document the parameters on DRF with Django REST Swagger 2.0 with @api_view? My example: @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def login(request): #not working """ username -- string password -- string """ username = request.data.get("username") password = request.data.get("password") -
POST ... 403 (Forbidden)
this is a massege i receive whan i click on list button. This is onclikc function and i am reciving POST (link) 403(Forbidden) send @ jquery-3.3.1.js:9600 ajax @ jquery-3.3.1.js:9206 odabir_vrste_namjene @ koprivnica:42 onclick @ koprivnica:151 This is my code: function odabir_vrste_namjene(vrsta_namjene_id){ $('#vrsta_namjene').val(vrsta_namjene_id); var zona_id = $('#zona').val(); $.ajax({ "type": "POST", "url": "/{{ slug }}/getng", // Mješamo Django template i JS, to je normalno "dataType": "json", "data": { "zona_id": zona_id, "vrsta_namjene_id": vrsta_namjene_id }, "success": function(data) { $('#nacin-gradnje').empty(); // Brišemo sve unutar tog UL taga $.each(data['nacin_gradnje_list'], function(i, ng) { // Dodajemo elemente koje je vratio server kao LI-eve u taj UL $("#nacin-gradnje").append("<li onclick=\"odabir_nacina_gradnje(" + ng['id'] + ")\">" + ng['naziv'] + "</li>"); }); $(".carousel").carousel("next"); } }); } also, This is the part that don't work out <div class="carousel-item h-100 slide-three"> <div class="h-100 d-flex align-items-center"> <div class="content-wrapper"> <input type="hidden" id="vrsta_namjene"> <label>Odaberite vrstu namjene:</label> <ul class="list-namjena" id="vrste-namjene"> {% for p in purpose_list %} <li onclick="odabir_vrste_namjene({{ p.id }})">{{ p.naziv }}</li> {% endfor %} </ul> <button class="btn btn-default" type="button">DALJE</button> </div> </div> </div> Can someone pls help me with this? -
Modelform is not populating its field with current values
I am making a view that will pre-populate its field incase if it is being edited again, otherwise serve a blank modelform. def ViewProfile(request,slug): ProfileResults=Profile.objects.filter(DiaryUser=slug) if request.method=='POST': if Profile.objects.filter(DiaryUser=slug).exists(): ProfileAlready=get_object_or_404(Profile,DiaryUser=slug) form=UpdateProfileForm(request.POST,request.FILES,instance=ProfileAlready) if form.is_valid(): form.save() else: form=UpdateProfileForm(request.POST,request.FILES) if form.is_valid(): ProfileUpdate=form.save(commit=False) ProfileUpdate.DiaryUser=slug ProfileUpdate.save() return redirect('Display',**{'slug':slug}) else: form=UpdateProfileForm() return render(request,'Mobile/ViewProfile.html',{'form':form,'slug':slug,'ProfileResults':ProfileResults}) but it is not pre-populting its fields otherwise it is working fine. Can anyone provide suggestion -
What is the meaning of source bin/activate in command prompt?
I am newbie of django , I have installed django in a given folder "Dev->django" but I am not able to start django. When I run a command "Source bin/activate" output will be like " (django) akriti@akriti:~/Dev/django$ " what is the meaning of "(django)" here? -
count the number of uses of each of the objects in another table
I have two models: class FirstTable(models.Model): name = models.CharField(...) class SecondTable(models.Model): examples = models.ManyToManyField(FirstTable) I have a function which counts how many times FirstTable is used in SecondTable's examples field: data = {} for i in FirstTable.objects.all(): data[i.name] = SecondTable.objects.filter(examples__exact=i).count() but is it possible to get the same data with one request? (aggregate or annotate ways) -
Python Django Update User and UserProfile in a same form
I am starting to learn python and django framework and messing around with UserChangeForm imported from django.contrib.auth.forms and now attempting to update the User info and User profile at the same time this is by combining the two fields. Here is my forms.py class EditProfileForm(UserChangeForm): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password') And here is my view.py def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/accounts/profile') else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'edit_profile.html', args) I was wondering if i can add the fields on my EditProfileForm class if that is possible? any suggestion would be great! fields = ('first_name', 'last_name', 'email', 'password','city','description') -
What is the recommended way to have CSRF protection in a Django Rest Framework + Angular application?
I have been struggling with a configuration between Django and Angular, and I am missing something. What is the recommended way of doing that? Angular has some XSRF protection, but it has changed since AngularJS and I found a lot of outdated information or manual. Django uses some defaults, but they don't behave well with Angular. What is the batteries-included way of solving CSRF between DRF and Angular? -
Extending auth_group_permission table in Django
I want to extend the auth_group_permission table. I know the table is made between many to many relationship with auth_permission table and auth_group table. If anyone have any ideas or suggestions to how to achieve it, then it will be very helpful. -
Sending webRTC video stream to server with django channels
I am trying to create a face detection web application written in django. The app works this way. The user navigates to the url The camera starts on the client machine Each frame is then sent to the server for face detection Processed frame is then displayed on the web page I understood I could not use opencv VideoCapture because, it only works on the server side. When I read online people asked me to use javascript and specifically webRTC to start live stream on the client side. So I found this tutorial which explains how to start webcam on the client machine with javascript. Now my question is how to send each frame from javascript on the client machine to opencv python on the server side? All this should happen in real time. So I cannot save the live video and then run the python code on the saved video. Some sites asked me to use AJAX to send data to the server side but I am not sure how to target each frame that is to be sent in the javascript code. This is my code so far CLIENT SIDE CAMERA ACCESS WITH webRTC <!DOCTYPE html> <html> <head> … -
Changing pre_save signal into post_save?Django
This are my models: class Purchase(models.Model): Total_Purchase = models.DecimalField(max_digits=10,decimal_places=2,blank=True, null=True) class Stock_Total(models.Model): purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal') stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') Total_p = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True) I have done this in my pre_save signal: @receiver(pre_save, sender=Purchase) def user_created1(sender,instance,*args,**kwargs): total = instance.purchasetotal.aggregate(the_sum=Coalesce(Sum('Total_p'), Value(0)))['the_sum'] instance.Total_Purchase = total I want change the pre_save signal into post_save signal.. How do I do that?and what changes I have to make in the function? Any idea? Thank you -
In Django project Media folder is not getting created
There is no media folder in the project, and i can see the media in db, but it won't load on template. With this error: Not Found: /DSC_0008.JPG settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('UserProfile.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Subquery Django by multiple columns
Is there a way to Subquery in Django by multiple columns? I want to get the latest instance of each type. sq = OrderedModel.objects.annotate( latest=Window( expression=Max("order"), partition_by=["type"] ) ) Something like this: OrderedModel.objects.filter(type=sq.type, sq.latest) -
How to apply autocomplete in manytomany field in django
I would like to apply the autocomplete option for my Preorder.preorder_has_products.through model in order to be able to load products with autocomplete(i tried unsuccessfully).Moreover, I have an inline implementation in order to be able to select for one preorder more than one product. The obstacle is that I have a manytomany field(preorder_has_products) as you can see below and I do not know how to implement the autocomplete. models.py class Preorder(models.Model): client = models.ForeignKey(Client,verbose_name=u'Πελάτης') preorder_date = models.DateField("Ημ/νία Προπαραγγελίας",null=True, blank=True, default=datetime.date.today) notes = models.CharField(max_length=100, null=True, blank=True, verbose_name="Σημειώσεις") preorder_has_products=models.ManyToManyField(Product,blank=True) def get_absolute_url(self): return reverse('preorder_edit', kwargs={'pk': self.pk}) class Product(models.Model): name = models.CharField("Όνομα",max_length=200) price = models.DecimalField("Τιμή", max_digits=7, decimal_places=2, default=0) barcode = models.CharField(max_length=16, blank=True, default="") eopyy = models.CharField("Κωδικός ΕΟΠΥΥ",max_length=10, blank=True, default="") fpa = models.ForeignKey(FPA, null=True, blank=True, verbose_name=u'Κλίμακα ΦΠΑ') forms.py class PreorderHasProductsForm(ModelForm): product = ModelChoiceField(required=True,queryset=Product.objects.all(),widget=autocomplete.ModelSelect2(url='name-autocomplete')) class Meta: model=Preorder.preorder_has_products.through exclude=('client',) def __init__(self, *args, **kwargs): super(PreorderHasProductsForm, self).__init__(*args, **kwargs) self.fields['product'].label = "Ονομα Προϊόντος" PreorderProductFormSet = inlineformset_factory(Preorder,Preorder.preorder_has_products.through,form=PreorderHasProductsForm,extra=1) my views.py for autocomplete class NameAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Product.objects.none() qs = Product.objects.all() if self.q: qs = qs.filter(product__istartswith=self.q) return qs my template is written based on this tutorial : https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html and finally my url for autocomplete: url(r'^name-autocomplete/$',views.NameAutocomplete.as_view(),name='name-autocomplete'), My result based …