Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirect LoginView to user specific account/profile URL
New to Django and running into a problem. I'm trying to configure my project so that when a user logs in, they are redirected to account/profile/ + username + / . I'm assuming I'm missing something fundamental but haven't been able to nail it down yet. My appreciation in advance for any help. models.py class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return '@{}'.format(self.username) class Meta: db_table = 'users' urls.py app_name = 'accounts' urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'), path('profile/<slug:slug>/', views.Profile.as_view(), name='profile') ] views.py class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('login') template_name = 'accounts/signup.html' class Profile(DetailView, LoginRequiredMixin): model = models.User slug_field = 'username' def get_context_data(self, request, **kwargs): context = super().get_context_data(**kwargs) context['username'] = request.user.username return context def get_success_url(self): return reverse_lazy('accounts:profile', kwargs={'slug': self.username}) login.html {% extends 'base.html' %} {% load bootstrap4 %} {% block bodyblock %} <div class="container"> <h1>Header Here</h1> <form class="login-form" method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Log In"> </form> </div> {%endblock%} profile.html {% extends 'base.html' %} {% block bodyblock %} <div class="container"> <h1>Welcome {{user.username}} !</h1> </div> {% endblock %} -
Laravel View Composer equivalent in Django
I'm learning django 2.1 is their any method in django which is equivalent to Laravel View::composer() method share data into specific templates. secondly how can i share data across different templates in django project which are frequently used. Note You might advise storing data in session but i'm looking for other solutions Thank You. -
Django APIView to log out of a user session
I have a Django module which is called from an SSO service. The service has a single signout function which makes a single GET request to a URL given to it during login. I'm trying to set up an APIView in Django to handle this logout. The origin service never checks the response; it only calls the GET URL once. I'm trying something like this for the APIView but keep getting session.DoesNotExist exceptions: class LogoutApi(APIView): def get(self, request, *args, **kwargs): s = Session.objects.get(session_key=kwargs.get('sk', '')) s.delete() return Response({'result': True}) I know I have a valid session but even when I try iterating through the Session.objects I can't find it. I also tried pulling the key from the SessionStore: class LogoutApi(APIView): def get(self, request, *args, **kwargs): sk = request.GET.get('sk', '') try: s = SessionStore(sk) del s[sk] return Response({'result': True}) except: self.logger.error(sys.exc_info()[0]) return Response({'result': False}) It still wasn't successful. Is there a way I can set up a GET API call to terminate a specific session? -
Django not saving immediately on new row entry?
I've got a django project set up as follows: myapp.models.py from django.db import models class BaseModel(models.Model): id = models.IntegerField(primary_key=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class Source(BaseModel): name = models.CharField(max_length=32, unique=True) base_url = models.ForeignKey('URL', on_delete=models.CASCADE) class URL(BaseModel): url = models.TextField(max_length=512, unique=True) url_source = models.ForeignKey('Source', on_delete=models.CASCADE, null=True, blank=True) In a separate functions.py file, I've got the following script which is intended to populate the database with some initial known data that will be referenced by all new data. i.e. indexing unknown number and target URL links found from a number of known Source websites. functions.py # Create non-runtime db access import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MY_PROJECT.settings") import django django.setup() sources = { 'website-one': {'base_url': 'https://www.website-one.com'}, 'website-two': {'base_url': 'https://www.website-two.com'}, 'website-three': {'base_url': 'https://www.website-three.com'}, } for name, meta in sources.items(): new_url = models.URL.objects.create(url=meta['base_url']) print(new_url.id) When this runs, the print function returns None, None, None which I interpret as meaning the new URL objects haven't been saved. If I inspect the database afterward I can see that each object is successfully created and has an id field as expected. My intent is to use this: new_url = models.URL.objects.create(url=meta['base_url']) To add a reference to a new Source in the next line as such: … -
with drf-yasg, how to supply patterns?
I have installed drf-yasg, and it's working great. The problem I've got is that it's a big app, and has a huge amount of endpoints for each type of frontend client, i.e. /admin/v1, /app/v1, ... So I thought it would be a good idea to separate documentation for each type, i.e urlpatterns += [ url(r'^/admin/swagger/$', admin_schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^/app/swagger/$', app_schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), ] So it looks as though drf-yasg supports this, via supplying patterns into the get_scheme_view: admin_schema_view = get_schema_view( openapi.Info( title="API", default_version='v1', description="The set of API endpoints used.", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@me"), license=openapi.License(name="BSD License"), ), patterns=?????, validators=['flex', 'ssv'], public=True, permission_classes=(permissions.AllowAny,), ) Now my guess was to supply a string, the same way as the first string when defining urls, such as patterns=r'^admin/v1/', which results in: File "/usr/local/lib/python3.6/dist- packages/rest_framework/compat.py", line 55, in get_original_route return urlpattern.regex.pattern AttributeError: 'str' object has no attribute 'regex' So with the documentation at drf-yasg docs: patterns – if given, only these patterns will be enumerated for inclusion in the API spec Exactly what type of object is needed here in order for to process patterns? I've tried looking around the django-rest-framework and Django source code on github, but couldn't find what type is actually needed, they are both … -
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.