Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
slug Django filed do we need this?
i am beginning with learn Django and get this data related "slug": A short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. For example, in a typical blog entry URL: https://www.djangoproject.com/weblog/2008/apr/12/spring/ the last bit (spring) is the slug. why do we need this and how to use? -
Django rest ModelViewSet many-to-many create
I have my model relationships as following: A Reader will have a Wishlist and a Wishlist will have many Books: class Reader(models.Model): user = models.OneToOneField(User) ... # A library has many readers which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE) class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) ... # A library has many books which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE) # Record the date whenever a new book is added, it will be helpful for showing new arrivals when_added = models.DateTimeField(auto_now_add=True, blank=True, null= True) reader = models.ManyToManyField('Reader', related_name='wishlist') My serializers: class ReaderSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') email = serializers.CharField(source='user.email') password = serializers.CharField(source='user.password') class Meta: model = Reader #fields = '__all__' #depth = 1 fields = ('id', 'username', 'email', 'password', 'phone', 'address', 'dob', 'which_library') def update(self, instance, validated_data): ... instance.which_library = validated_data.get('which_library', instance.which_library) instance.save() return instance def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) user.set_password(user_data['password']) user.save() reader = Reader.objects.create(user=user, **validated_data) return reader class BookSerializer(serializers.ModelSerializer): wishlist = ReaderSerializer(many=True, read_only=True) class Meta: model = Book fields = '__all__' I can already perform CRUD operations with Reader, I want to now add books to a specific Reader's wishlist. My view: class ReaderViewSet(viewsets.ModelViewSet): serializer_class = ReaderSerializer def get_queryset(self): readers = Reader.objects.filter(which_library=self.kwargs.get('library_id')) return readers @detail_route(methods=['post']) def wishlist(self): return Response('OK') … -
Trigger model method on creation or field change
Assume, that I have this model in django: class Example(models.Model): name = models.CharField(max_length=100) number = models.IntegerField(unique=True) x = models.FloatField(null=True) y = models.FloatField(null=True) z = models.FloatField(null=True) v = models.FloatField(null=True) def get_z(self): z = x / y self.z = z self.save() def get_v(self): v = z * x self.v = v self.save() When I create an object with admin panel then I provide only name, number, x and y fields. I need to z and v field calculate automatically on object creation or whenever any of fields changes they value. For now it's working via making: z_value = property(get_z) and putting z_value in list_display in admin panel, then when I go there, values are saved. -
Django foreign key with different model field values
I want to create a foreign key relationship in a model, where it actually provides a select dropdown for the model form based on another field value of the model. Normally dropdown shows the values of __str__ methods return value. I want to keep this also since it used in other places. For example, consider two models Order and Item. Item has a field called item_code and item_name. __str__ will return item_name. Order model will have foreign key to Item model. But I want it provides the item_code field values in the dropdown for item selection. How can I achieve this without changing general foreign key behavior? -
Django Database create_or_update error
So the definition for the pcaps table is : class Pcaps(models.Model): uuid = models.CharField(max_length=50, unique=True) filename = models.CharField(max_length=200, default='') datetime = models.DateTimeField(default=datetime.now, blank=True) filehash = models.ForeignKey(Malwares) systemuuid = models.ForeignKey(ClonedSystem) the definition for the malware table is: class Malwares(models.Model): name = models.CharField(max_length=100) filehash = models.CharField(max_length=100, unique=True) the code from the views file is: Pcaps.objects.update_or_create(filename=pcapname, filehash=filehash, systemuuid=uuid) the malware value is instantiated at: Malwares.objects.update_or_create(name=name, filehash=malwarehash) the error I am getting is: invalid literal for int() with base 10: 'ed01ebfbc9eb5bbea545af4d01bf5f1071661840480439c6e5babe8e080e41aa' (ed01... being the filehash value) What error am I making here? -
Django admin set and user view permission
I need to add to my django application the view permission. I need that some users have the permission to see all values inserted in some models but do not have the permission of adding/changing/deleting them. In accordance to django docs I've added "default_permissions" expression to my model meta information, for example: class Mymodel(models.Model): name = models.TextField(verbose_name=u"Name") class Meta: default_permissions = ('add', 'change', 'delete', 'view') Then I've changed my group permission and added it to some users. The problem is that when these users go to the view page they receive an 403 error. Do I have to change my "changelist_view" function? def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} extra_context['model_title'] = Campaign._meta.verbose_name_plural return super(MymodelAdmin, self).changelist_view(request, extra_context=extra_context) -
django-admin starproject can't find Module django is installed with subprocess.run
I'm running a script to install the virtual environment and then install all the dependencies through subprocess.run. Everything goes great until I have to run django-admin startproject mysite. Somehow, I get Traceback (most recent call last): File "/Users/myuser/.virtualenvs/mysite/bin/django-admin.py", line 2, in <module> from django.core import management ModuleNotFoundError: No module named 'django' To make things even more strange, if you directly on the command line run pip unistall djangoand then pip install django==1.11it works, however the user will have to do that manually, which is not what I was going for. Things I checked so far: which python resulting /Users/myuser/.virtualenvs/mysite/bin/python which pipresulting /Users/myuser/.virtualenvs/mysite/bin/pip which django-admin resulting /Users/myuser/.virtualenvs/mysite/bin/django-admin I opened a shell and imported django and got the module -
Django aggregation multiple filters
I have a Django project that allows users to create their own Projects and add multiple Skills to each Project. I am trying to write a view that will allow me to display the name of each Skill as well as the Count of that Skill for all of that particular user Profile's Projects that are published. For example, if a user has three projects where they've added the Skill "HTML" I'd like to show HTML (3) on their Profile, and so on. Below is my current code which mostly works however it displays the count for that Skill from ALL user projects and not the specific user whose profile is being viewed. Models: #accounts/models.py class Profile(models.Model): #... skills = models.ManyToManyField('skills.skill') #projects/models.py class Project(models.Model): user = models.ForeignKey(User) #... published = models.BooleanField(default=False) skills = models.ManyToManyField('skills.skill') #... #skills/models.py class Skill(models.Model): name = models.CharField(max_length=100) Views: #accounts/views.py def profile(request, username): user = get_object_or_404(User, username=username) skill_counts = Skill.objects.annotate(num_projects=Count('project')).filter(project__user_id=user.id).order_by('-num_projects')[:10] return render(request, 'accounts/profile.html', { 'user': user, 'skill_counts': skill_counts, }) Template: #accounts/templates/accounts/profile.html {% for skill in skill_counts %} <div class="skill-container"> <div class="label-skill">{{ skill.name }}</div> <div class="label-skill-count"> {{skill.project_set.count}}</div> </div> {% endfor %} Any help here would be much appreciated. Thanks in advance. -
Set Django session variables through channels (http_session)
According to the Django channel docs, You get access to a user’s normal Django session using the http_session decorator - that gives you a message.http_session attribute that behaves just like request.session. You can go one further and use http_session_user which will provide a message.user attribute as well as the session attribute. Is there anyway I can set a session variable like so? if 'username' not in message.http_session: message.http_session['username'] = 'temp' -
Issue loading admin.site.urls after changing the settings folder
I re-organized Django,the following way: config - settings - base.py - local.py urls.py wsgi.py In base.py/local.py: ROOT_URLCONF = 'config.urls' WSGI_APPLICATION = 'config.wsgi.application' In manage.py I changed: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") In wsgi.py I changed: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") I have the following error on runserver: \django\contrib\admin\sites.py", line 269, in get_urls path('%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)), AttributeError: 'AccountAdmin' object has no attribute 'urls' It is related to this line: path('admin/', admin.site.urls), # Django 2.0 syntax If I comment that line I get the following error: django\contrib\admin\sites.py", line 79, in check if modeladmin.model._meta.app_config in app_configs: AttributeError: 'AccountAdmin' object has no attribute 'model The app admin is in installed app, I don't know what is creating this issue. -
Django using Abtract model
I am new in Django. There is abstract model in Django? how can I use it? Do it create the tables both to base class and children? I am try to understand the Django documentation in this topic but failed. -
Event driven API design for full duplex communication with Client
I have a Django backend API and a React Native App listening for new/incoming sales requests triggered by other APIs. What are the best design approaches in designing an API notifying a Client App for new sales rather than the Client App polling the API every minute or so. -
How to make an Inner Join in django?
I want to show in a html the name of the city, state and country of a publication. But they are in diferent tables. Here is my models.py class country (models.Model): country_name = models.CharField(max_length=200, null=True) country_subdomain = models.CharField(max_length=3, null=True) def __str__(self): return self.country_name class countrystate (models.Model): state_name = models.CharField(max_length=200, null=True) country = models.ForeignKey(country, on_delete=models.CASCADE, null=True) importance = models.IntegerField(null=True) def __str__(self): return self.state_name class city (models.Model): city_name = models.CharField(max_length=200, null=True) countrystate = models.ForeignKey(countrystate, on_delete=models.CASCADE, null=True) def __str__(self): return self.city_name class publication(models.Model): user = ForeignKey(users, on_delete=models.CASCADE, null=False) title= models.CharField(max_length=300, null=True) country=models.ForeignKey(country, on_delete=models.CASCADE, null=True) countrystate=models.ForeignKey(countrystate, on_delete=models.CASCADE, null=True) city=models.ForeignKey(city, on_delete=models.CASCADE, null=True) def __str__(self): return self.title Here is my views.py def publications(request): mypublications = publication.objects.filter(user_id=request.session['account_id']) dic.update({"plist": mypublications }) return render(request, 'blog/mypublications.html', dic) In a django view, what is the equivalent of the next sql query? SELECT p.user_id, p.title, c.cuntry_id, c.country_name, s.state_id, s.state_name, y.city_id, y.city_name FROM publication AS p INNER JOIN country AS c ON c.id = p.country_id INNER JOIN countrystate AS s ON s.id = p.countrystate_id INNER JOIN city AS y ON y.id = p.city_id -
django class view Overlapping
I am not good at English. Please understand me. I'm creating a blog in Django. I am making it into class view, but I want to see a replay list and form in the post details view. like this enter image description here POST detailview has already been implemented and I don't know how to add comments. Should I be function view? Give me some advice. -
Heroku Django app not loading static files (404 Not Found)
I have been trying to deploy a django app onto heroku. However, it's not able to obtain the static files. I ran collecstatic on heroku and there is a static folder in the root directory of the app that contains the correct files: ~/static/rest_framework/css/bootstrap.min.css. Settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') cURL: curl 'https://xxx.herokuapp.com/static/rest_framework/css/bootstrap.min.css' \ -XGET \ -H 'Referer: https://xxx.herokuapp.com/users/login' \ -H 'Accept: text/css,*/*;q=0.1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7' -
Django: Submitting same form multiple times causes 403 CSRF exception
I have a form which creates a trip. This form is submitted via AJAX, trip created and then, the form inputs are cleared so user can create another item without refreshing the page. The problem is that after first submit, Django returns: CSRF verification failed. Request aborted. I know that problem is that CSRF Token has been chaned but it wasn't reflected in users cookies since the page wasn't refreshed. View class TripCreationView(LoginRequiredMixin, SuccessMessageMixin, CreateView): form_class = TripCreationForm template_name = 'trips/add_new_trip.html' success_message = _('New trip has been added') context_object_name = 'trip_creation_form' def post(self, request, *args, **kwargs): return super(TripCreationView, self).post(self, request, *args, **kwargs) def get_form_kwargs(self): kwargs = super(TripCreationView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def get_context_data(self, **kwargs): context = super(TripCreationView, self).get_context_data(**kwargs) context['trip_creation_form'] = context['form'] return context def get_initial(self): initial = super(TripCreationView, self).get_initial() initial.update({k: v for k, v in self.request.GET.iteritems()}) return initial def form_valid(self, form): if self.request.is_ajax(): form.save() return JsonResponse({'status':'OK'}) def get_success_url(self): return self.request.POST.get('success_url') or reverse('frontend:homepage') But I don't know how to make this work. Do you have any ideas? -
Django - Bootstrap Dropdown Lists Not Working
I'm working on my Django web application and I can't seem to get the dropdown list to actually drop down when clicked. <div class="panel panel-default"> <div class="panel-body"> <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Actions <span class="caret"></span></button> <ul class="dropdown-menu"> <li><a href="{% url 'start' uuid=uuid %}">Start</a></li> <li><a href="{% url 'clone' uuid=uuid %}">Clone</a></li> <li><a href="{% url 'stop' uuid=uuid %}">Stop</a></li> <li><a href="{% url 'paranoidfish' uuid=uuid %}">Run Anti-Anti-Forensics Checker</a></li> </ul> </div> and by request my urls.py, although i'm not entirely sure how that's related urlpatterns = [ #multiurl( url(r'^$', views.index, name='index'), #url(r'^$', views.transfer, name='transfer'), url(r'^malware/$', views.malware, name='malware'), # Add this /malware/ route url(r'^pokedex/$', views.pokedex, name='pokedex'), # Add this /malware/ route url(r'^about/$', views.about, name='about'), # Add this /about/ route #url(r'^(?P\d+)/results/$', views.results, name='results'), # url(r'^(?P<>\d+)/Clone/$', ) url(r'^clone/(?P<uuid>[\w\-]+)$', views.clone, name='clone'), url(r'^start/(?P<uuid>[\w\-]+)$', views.start, name='start'), url(r'^paranoidfish/(?P<uuid>[\w\-]+)$', views.paranoidfish, name='paranoidfish'), url(r'^stop/(?P<uuid>[\w\-]+)$', views.stop, name='stop'), url(r'^transfer/(?P<uuid>[\w\-]+)$', views.transfer, name='transfer'), # url(r'^(?P<uuid>[\w\-]+)/(?P<malware>[\w\-]+)$', views.execute, name='execute'), url(r'^execute/(?P<uuid>([0-9\-a-f]+))/(?P<malware>[-A-Z\0-9\-a-z]+)/$', views.execute, name='execute'), url(r'^transfer/(?P<uuid>([0-9\-a-f]+))/(?P<malware>[-A-Z\0-9\-a-z]+)/$', views.transfer, name='transfer'), #) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
How to deal with a variable string in django queryset?
I am trying to write a django queryset. Review.objects.filter(user__exact=user).count() The problem is that the "user__exact" has to match with the current value of the "cuser" variable (the user who is currently logged in), and then return the count of the reviews submitted by that user. But if I do that I am getting this error. TemplateSyntaxError at /dashboard/ Could not parse the remainder: '(user__exact=cuser).count()' from 'Review.objects.filter(user__exact=user).count()' Any ideas on how to make it work? -
Error 400 in IONIC 3 when sending post to API on localhost of Django REST
Provider rest.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { HttpHeaders } from '@angular/common/http/src/headers'; @Injectable() export class RestProvider { apiUrl = 'http://127.0.0.1:8000' constructor(public http: HttpClient) { console.log('Hello RestProvider Provider'); } getUsers() { return new Promise(resolve => { this.http.get(this.apiUrl+'/users/').subscribe(data => { resolve(data); }, err => { console.log(err); }); }); } addUser(data){ console.log(JSON.stringify(data)); return new Promise((resolve, reject) => { this.http.post(this.apiUrl+'/users/', JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }) .subscribe(res => { resolve(res); }, (err) => { reject(err); }); }); } } Page adduser.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { RestProvider } from '../../providers/rest/rest'; @IonicPage() @Component({ selector: 'page-adduser', templateUrl: 'adduser.html', }) export class AdduserPage { user = { email: '', groups: { url: '', name: '' }, url: '', username: ''}; constructor( public navCtrl: NavController, public navParams: NavParams, public restProvider: RestProvider) { } ionViewDidLoad() { console.log('ionViewDidLoad AdduserPage'); } saveUser(){ console.log(this.user); this.restProvider.addUser(this.user).then((result) => { console.log(result); }, (err) => { console.log(err); }); } } Page adduser.html <ion-content padding> <h2>Add User</h2> <form (ngSubmit)="saveUser()"> <ion-item> <ion-label>Username</ion-label> <ion-input type="text" [(ngModel)]="user.username" name="username"></ion-input> </ion-item> <ion-item> <ion-label>Email</ion-label> <ion-input type="email" [(ngModel)]="user.email" name="email"></ion-input> </ion-item> <button ion-button type="submit" block>Add User</button> </form> </ion-content> This error appears when I try … -
Widget attribute does not work
I have two forms and a formset. I have given __init__ for both the forms. However in my template only my POBodyForm is rendered with the attributes. Looks like __init__ of POHeaderForm is not working. I am not sure what is the error. Can someone please advise? I have been using the similar __init__ class all over my project and this the first time a form is refusing to render or causing me an issue. Relevant Form Code: class POHeaderForm(forms.ModelForm): class Meta: model = POHeaderModel fields = '__all__' def __init__(self, *args, **kwargs): super(POHeaderForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = {'class': 'form-control form-control-sm'} class POBodyForm(forms.ModelForm): class Meta: model = POBodyModel fields = '__all__' def __init__(self, *args, **kwargs): super(POBodyForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = {'class': 'form-control form-control-sm'} POFormSet = forms.inlineformset_factory(POHeaderModel, POBodyModel,form=POBodyForm, extra=1) and the view is as follows: class PurchaseOrderCBV(CreateView): model = POHeaderModel fields = '__all__' success_url = reverse_lazy('purchase_order') def get_context_data(self, **kwargs): data = super(PurchaseOrderCBV, self).get_context_data(**kwargs) if self.request.POST: data['formbody'] = POFormSet(self.request.POST) else: data['formbody'] = POFormSet() return data def form_valid(self, form): context = self.get_context_data() formbody = context['formbody'] with transaction.atomic(): self.object = form.save() if formbody.is_valid(): formbody.instance = self.object formbody.save() return super(PurchaseOrderCBV, self).form_valid(form) -
Django User model foreign key failed
I am using django 2.0. For users I am using the model django.contrib.auth.models.User. I have stored a user with username john in it. I have a Post model which uses a User model as ForeignKey. This is my models.py: from django.db import models from django.contrib.auth.models import User class Post(models.Model): post_content = models.CharField(max_length=140) post_date = models.DateTimeField('post date') post_user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.post_content ...In my views.py I am creating a post with: from django.contrib.models import User Post.objects.create(post_content=post_text, post_date=timezone.now(),post_user=User.objects.get(username='john')) ...In one part of the code. When I run I get this error: FOREIGN KEY constraint failed IntegrityError at / And it points to the line in which I create the user in views.py. Any guidance appreciated. Thank you :-). -
Javascript & Django - Confirm() cancel does not prevent deletion
I'm using Django in my project and I'm getting some problems with confirm function in order to prevent items deletion from datatable option. Despite I cancel in the confirm pop-up, button still sends me to the default link href and the object is deleted. This is my HTML: <a class='btn btn-danger btn-xs' id="elimina-objeto" onclick="confirmaEliminacion()" href="{% url 'eliminarQueja' queja.id %}">Eliminar</a> And my JS: function confirmaEliminacion() { var res = confirm("Va a eliminar el objeto seleccionado. Si desea continuar, pulse aceptar."); if (res) { return false; } else { document.getElementById("elimina-objeto").href = "#"; } } } -
Using Django forms to get information from more than 1 model
I am using Django to create a gym app. In this app users can share workouts that have various exercises in them. I have three models> Workout ( which stores the names of the different workouts and the author of the post and time of creation), Exercise ( which stores the name of the exercises and a description of each) and WorkoutExercises ( which links an exercise to a workout and stores the number of sets and reps). Currently, I am trying to make a form that will allow a user to create a workout and add exercises to it (each with various sets and reps) however, I have found that i cannot use more than 1 model in my Form. How do I go about getting information from the user so I can put it in the database so that it all links up? -
django skips to much in loop one to many relation
I did learn a lot from this site, and also searched a lot to solve my problem. I tried everything the past days but i did not succeed, so please help me with the following. the output is like this member1 - 2017 - 2018 (this member does not have 2014-2015 or 2016) member2 - 2017 (this member does not have 2014-2015-2016 or 2018) member3 - - 2018 (this member does not have 2014-2015-2016 or 2017) member4 -nothing displayed (this member does have 2014 and 2018) the loop, loops through Leden, and skips every Leden record which has a year before 2017 (like in the views.py exclude). but i want to exclude only the Contributie year before 2017. how can i do this? my models.py : class Leden(models.Model): id = models.AutoField(primary_key=True) voornaam = models.CharField(max_length=255, blank=True) achternaam = models.CharField(max_length=255, blank=True) class Contributie(models.Model): id = models.AutoField(primary_key=True) ledenid = models.ForeignKey(Leden, on_delete=models.CASCADE) jaar = models.CharField(default=date.today().year, max_length=4, blank=True) my view.py: class IndexView(generic.ListView): template_name = 'xxx/xxx.html' context_object_name = 'latest_list' def get_queryset(self): thisyear = date.today().year twoyearsago = thisyear - 2 return Leden.objects.exclude(contributie__jaar__lte=twoyearsago) and a part of my template: {% if latest_list %} {% for leden in latest_leden_list|dictsort:"achternaam" %} <tr> <td>{{ leden.id }}</td> <td>{{ leden.voornaam }}</td> <td>{{ leden.achternaam … -
Django Admin, including reverse foreignkeyfields on page
I have the following two models: class Seller(models.Model): name = models.Charfields(max_lenght=500) (... more fields, but no foreignkeys to anyone) class Ad(models.Model): seller = models.Foreignkey(Seller, related_name='ads') (... more fields that are not relevant to this question ) Now I want to include the Seller information on age 'Ad' page within the Django admin. I tried doing admin-inline like so: class SellerInline(admin.TabularInline): model = Seller view_on_site = False class AdAdmin(admin.ModelAdmin): list_display = ['item', 'title', 'seller', 'price'] list_filter = ('item', 'item_state', 'transaction_type', ) view_on_site = False raw_id_fields = ('seller', 'searches') search_fields = ['title', 'seller__username'] inlines = [ SellerInline, ] But this throws the following error: <class 'scraper.admin.SellerInline'>: (admin.E202) 'scraper.Seller' has no ForeignKey to 'scraper.Ad'. Now, some googling around informed me of the fact that reverse-relations dont work with the Inline admin. I could ofcourse reverse the foreignkey on the models. But each seller could potentially have hundreds of ads, (and the ad model has around 20 fields), which would lead to a very unwieldy seller page. Does anyone know of a way to include the Seller fields on the Ad page within the admin, or is this really impossible?