Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple Models in one Admin Screen
I have models: class Acessories(models.Model): clother = models.ForeignKey(Clother, on_delete=models.CASCADE) acessories_type = models.ForeignKey(AcessoriesType, on_delete=models.CASCADE) name = models.CharField(max_length=30, blank=True) class Clother(models.Model): MALE = 'MA' FEMALE = 'FE' UNISEX = 'UN' GENDER_CHOICES = ((MALE, 'Male'), (FEMALE, 'Female'), (UNISEX, 'Unisex')) commodity = models.ForeignKey(Commodity, related_name='commodity', on_delete=models.CASCADE) color = models.ManyToManyField(Commodity, related_name='color') material = models.ManyToManyField(Commodity, related_name='material') gender = models.CharField(max_length=2, choices=GENDER_CHOICES, default=UNISEX) How can I make it in one Admin screen? Need to see and edit this as it was one model. Thanks! -
Grouping a query set multiple times
I have the following query to get events from the database and group them by month. EventsByMonth = Tracking.objects.filter(ad_org="Acme").extra(select=bymonth_select).values('month').annotate(events=Count('id')).order_by('-month') The output is: [{'events': 1503, 'month': datetime.datetime(2018, 6, 1, 0, 0)}, {'events': 32747, 'month': datetime.datetime(2018, 5, 1, 0, 0)}] Is it possible to group again by another variable? Specifically, these events can be broken down further into event types, which are stored in a field called action. The ideal output would look like this: [{'events': 1503, 'month': datetime.datetime(2018, 6, 1, 0, 0), 'action1events': 200, 'action2 events':1303}, {'events': 32747, 'month': datetime.datetime(2018, 5, 1, 0, 0), 'action1events': 32000, 'action2 events':747}] -
Combining two query sets across a unique key
I have two query sets that I'd like to combine with the 'month' being the unique key to combine on. **Query Set 1 (Impressions) ** [{'events': 1503, 'month': datetime.datetime(2018, 6, 1, 0, 0)}, {'events': 32747, 'month': datetime.datetime(2018, 5, 1, 0, 0)}] **Query Set 2 (Clicks) ** [{'events': 163, 'month': datetime.datetime(2018, 6, 1, 0, 0)}, {'events': 4184, 'month': datetime.datetime(2018, 5, 1, 0, 0)}, {'events': 5049, 'month': datetime.datetime(2018, 4, 1, 0, 0)}, {'events': 592, 'month': datetime.datetime(2018, 3, 1, 0, 0)}] ` Is it possible to combine them such that the output would look like this? [{'clicks': 163, 'impressions': 1503, 'month': datetime.datetime(2018, 6, 1, 0, 0)}, {'clicks': 4184, 'impressions':32747, 'month': datetime.datetime(2018, 5, 1, 0, 0)}, {'events': 5049, 'month': datetime.datetime(2018, 4, 1, 0, 0)}, {'events': 592, 'month': datetime.datetime(2018, 3, 1, 0, 0)}] -
Django Writable Nested Serializers Update
I can not update records with a patch request, I have seen that I must add the update method, but I can not understand how it actually works. I'm new to django. The modes is mysql: model.py class Medida(models.Model): descripcion = models.CharField(max_length = 100) class Meta: ordering = ('descripcion',) class Sucursal(models.Model): descripcion = models.CharField(max_length = 100) class Meta: ordering = ('descripcion',) class Item(models.Model): codigo = models.CharField(max_length = 4) descripcion = models.CharField(max_length = 100) class Meta: ordering = ('codigo',) class Almacen(models.Model): item = models.ForeignKey(Item, on_delete = models.CASCADE) peso = models.FloatField() medida = models.ForeignKey(Medida, on_delete = models.CASCADE) sucursal = models.ForeignKey(Sucursal, on_delete = models.CASCADE) class Meta: ordering = ('item',) serializers.py class MedidaSerializer(serializers.ModelSerializer): class Meta: model = Medida fields = ('id', 'descripcion') class SucursalSerializer(serializers.ModelSerializer): class Meta: model = Sucursal fields = ('id', 'descripcion') class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id', 'codigo', 'descripcion') class AlmacenSerializer(serializers.ModelSerializer): medida = MedidaSerializer(read_only = True) item = ItemSerializer(read_only = True) sucursal = SucursalSerializer(read_only = False) class Meta: model = Almacen fields = ('id', 'item', 'peso', 'medida', 'sucursal') The json answer is correct, but when you want to modify, in this case a branch with an object. Does not work. For example: Request: { "id": 2, "item": { … -
can't see the file created in python
def _store_file(self, logVal): if not os.path.exists('logs'): print("[INFO] creating directory") a = os.makedirs("logs") print("INFO create Dir result: " + str(a)) f = None try: print("{INFO} Trying to open the file for writing logs") f = open('logs/' + self.conf['filename'], 'w') print("{INFO} realpath of file is: " + os.path.realpath(f.name)) print("{INFO} abs path of file is: " + os.path.abspath(f.name)) res = f.write(str(logVal)) print("INFO file write: " + str(res)) except IOError as er: print("[INFO]" + str(er)) finally: f.close() print("[INFO] WRITTING TO FILE") print("sdfjsbdfkjbsdfkjbskjdfbskjfbskjbfkjsdbsdfksds", file=open('logs/temp.txt', 'w')) I have written a middleware that sends the request data to a module that stores logs in a file debug.log inside folder logs. The code for writting to file is not giving any errors, but I can't see any folder named log nor any file named debug.log. Further when I try to see full path of the file it gives /code/logs/debug.log I have searched my whole system but can't find this path -
valueerror invalid literal for int () with base 10 django in migrate, when deploying django project in heroku
models.py from __future__ import unicode_literals from django.db.models.signals import post_save from django.db import models # Create your models here. from django.contrib.auth.models import User class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name = 'owner',null=True) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.remove(new_friend) class Post(models.Model): post=models.CharField(max_length=500) user=models.ForeignKey(User) data = models.DateTimeField(auto_now=True) class UserProfileManager(models.Manager): def queryset(self): return super(UserProfileManager,self).get(queryset).filter(city='surat') class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100,default='') city = models.CharField(max_length=100,default='') website = models.URLField(default='') phone = models.IntegerField(default=0) image = models.ImageField(upload_to='profile_image',blank=True) surat = UserProfileManager() def __str__(self): return self.user.username def create_profile(sender,**kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile,sender=User) views.py from django.http import HttpResponse from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from tutorial import views from accounts.forms import Registrationform,EditProfileForm from django.contrib.auth.forms import UserChangeForm,PasswordChangeForm from django.contrib.auth.models import User from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView from .forms import HomeForm from .models import Post,Friend class HomeView(TemplateView): template_name = 'accounts/home.html' def get(self,request): form = HomeForm() posts=Post.objects.all() users = User.objects.exclude(id=request.user.id) friend =Friend.objects.get(current_user=request.user) friends = friend.users.all() args={ 'form':form,'posts':posts,'users':users,'friends': friends } return render(request,self.template_name, args) def post(self,request): form = HomeForm(request.POST) if form.is_valid(): post=form.save(commit=False) post.user=request.user post.save() text =form.cleaned_data['post'] form = HomeForm() return … -
Django select option - displaying image in template
I'm trying to create a select button that shows images with their title for a user to choose one from. template <select id="fabric-select" name="select-id"> {% for item in fabric %} <option value="{{item.id}}">{{item.fabric_cover.url}}</option> <option value="{{item.id}}"><img src="{{item.fabric_cover.url}}" alt="fabric picture">{{item.name}}</option> <option value="{{item.id}}" data-image="{{item.fabric_cover.url}}"></option> {% endfor %} </select> Tried different options but none of them show the image itself. First option just shows me the static link of the image. Second option shows the name but nothing else and the third option shows an empty field. From my view: class ProductListView(ListView): queryset = Product.objects.all() def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj fabric_obj = Fabric.objects.all() context['fabric'] = fabric_obj return context Model class Fabric(models.Model): name = models.CharField(max_length=120) fabric_cover = models.ImageField(upload_to='fabric_images', blank=False) Unsure if it's simply not possible to grab the picture directly an put it in the option, if I'm using the wrong code for my template to output it or if I'm missing something to make this work. -
Django: can't find function
I'm trying to make a button turn on/off led throgh html, but django can't find function in views.py. What am I doing wrong? Python 2.7,Django 1.6.5. HTML code: <button type="submit" class="btn btn-primary" onclick="call_counter('/FirstApp/led_on/');">Led ON</button> <button type="submit" class="btn btn-primary" onclick="call_counter('/FirstApp/led_off/');">Led OFF</button> views.py code: # coding: utf-8 from django.shortcuts import render,HttpResponse from django.template import RequestContext, loader import time from time import sleep from subprocess import call, check_output # create here def index(request): call(["gpio","mode","4","in"]) global state #state=1 state=int(check_output(["gpio","read","4"])) #print(state) context={'Status': state} return render(request, 'FirstApp/index.html',context) def led_on(request): global gp gp=True #call(["gpio","mode","1","pwm"]) call(["gpio","mode","1","out"]) return HttpResponse(status=200) def led_off(request): global gp gp=False call(["gpio","mode","0","out"]) return HttpResponse(status=200) urls.py code from django.conf.urls import url from FirstApp import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^led_on/', views.led_on, name='led_on'), url(r'^led_off/', views.led_off, name='led_off'), ] -
Django: Adding Many to Many field
I am currently struggling to assign a many-to-many field to my newly created objects. Anyone knows what I am doing wrong? Note: I have one solution in mind which is first creating the ticket, and then afterwards trying to assign it. Might that be the way to do it? #Create ticket_tax assign_event = Event.objects.all() for event in assign_event: TicketTax.objects.create( event=event, name=lorem, percentage=0.19, ) # Create tickets price_gross = ['40.60', '30.30', '100.40', ] name = ['Early Bird', 'Regular Ticket', 'Last Minute Ticket', ] assign_event = Event.objects.all().first() assign_ticket_tax = TicketTax.objects.all().first() for i in range(len(price_gross)): Ticket.objects.create( event=assign_event, ticket_tax=assign_ticket_tax.add(), price_gross=price_gross[i], name=name[i], description='ABC', start_at='2018-05-26 18:12:58.556925+02', end_at='2018-05-29 18:12:58.556925+02', quantity=100, status='On sale', ) models.py class TicketTax(models.Model): event = models.ForeignKey( Event, on_delete=models.PROTECT, related_name='ticket_taxes' ) name = models.CharField(max_length=100) percentage = models.DecimalField( max_digits=5, decimal_places=4 ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Ticket(models.Model): event = models.ForeignKey( Event, on_delete=models.PROTECT, related_name='tickets' ) ticket_tax = models.ManyToManyField(TicketTax, blank=True) price_gross = models.DecimalField( max_digits=25, decimal_places=2 ) name = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) start_at = models.DateTimeField() end_at = models.DateTimeField() quantity = models.PositiveIntegerField() status = models.CharField( max_length=8, choices=TicketStatus.CHOICES ) is_archived = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name -
Do I need to use 'load static' twice on overall layout and header in Django?
I'm on a project in Django, and the problem is like this. My site have a overall layout like 'layout.html' which includes some static files, links in and 'header.html' including navigator, 'footer.html' including some links in . But Both of 'layout.html' and 'header.html' uses static files so I think one command {% load static %} on first line in 'layout.html' can affect both 'layout.html' and 'header.html' because 'layout.html' includes 'header.html'! But it doesn't work, it works only when {% load static %} in both files. Maybe my explanation is hard to understand, so I will write my code very shortly. 'layout.html' {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link href="{% static 'onepage-scroll.css' %}" rel="stylesheet" type="text/css"> </head> <body> {% include 'header.html' %} {% block content %} {% endblock %} {% include 'footer.html' %} </body> </html> 'header.html' {% load static %} <nav id="navi"> <h3><a href="{% url 'main:home' %}"><img src="{% static 'logo.jpg' %}"></a></h3> </nav> I think this is not a good implementation because there are 2 times of loading staticfiles. Is there another way to solve this? -
Parsing List of Dictionaries with multiple same Keys
I started with this list of dictionaries. [{'allow_day_and_time': {'day': 'Monday', 'start': 9, 'end': 18}}, {'allow_day_and_time': {'day': 'Tuesday', 'start': 9, 'end': 18}}, {'allow_day_and_time': {'day': 'Wednesday', 'start': 9, 'end': 18}}, {'allow_day_and_time': {'day': 'Thursday', 'start': 9, 'end': 18}}, {'allow_day_and_time': {'day': 'Friday', 'start': 9, 'end': 18}}] I applied this. index = 0 while index < len(availability_constraints): for key in availability_constraints[index]: print(availability_constraints[index][key]) index += 1 results in {'day': 'Monday', 'start': 9, 'end': 18} {'day': 'Tuesday', 'start': 9, 'end': 18} {'day': 'Wednesday', 'start': 9, 'end': 18} {'day': 'Thursday', 'start': 9, 'end': 18} {'day': 'Friday', 'start': 9, 'end': 18} It's possible that I could be returned multiple start and end vales for any of days returned for example Monday start 9, finish 11, Monday Start 13, finish 18. What I'm struggling with is how to get the start and finish time for the days retuned keeping in mind I might be returned multiple start and end times for the same day. Any pointers would be a big help. -
Post request via Axios fails while it succeeds from POSTMAN . How?
I am trying to perform a post request with axios to an endpoint on a ubuntu vps(a django backend) . The api responds 201 created after a successful post request. Using Postman, i am able to perform a successful post request but when i am trying it with Axios, I can see the exceptions being catched in the console (i have used console.log). Here's how i am doing it via Axios : . . . axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = 'X-CSRFToken' // Tried without headers as well var headers = {'Content-Type': 'application/x-www-form-urlencoded'} axios.post('http://127.0.0.1:8000/api/v1/subscribe/',data_str,headers) .then(function(response) { console.log('saved successfully'); // this.isHidden = false; alert("Subscription succesful !!"); console.log(response) }).catch((error) =>{ if(error.response){ console.log('1..........Response Error'); console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if(error.request){ // This part gets printed in the browser console. No idea why console.log('2..........Request Error'); console.log(error.request); } else{ console.log('3..........Other error'); console.log('Error', error.message); } console.log(error.config); } ); var headers = {'Content-Type': 'application/x-www-form-urlencoded'} axios.post('http://127.0.0.1:8000/api/v1/subscribe/',data_str,headers) .then(function(response) { console.log('saved successfully'); // this.isHidden = false; alert("Subscription succesful !!"); console.log(response) }).catch((error) =>{ if(error.response){ console.log('1..........Response Error'); console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if(error.request){ console.log('2..........Request Error'); console.log(error.request); } else{ console.log('3..........Other error'); console.log('Error', error.message); } console.log(error.config); } ); **Few CORS configurations in my django rest api : CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = … -
`NOT NULL constraint failed:` when try to Create a User
I encounter error NOT NULL constraint failed: when intend to create a User account: The model data code: class ActivateCode(models.Model): """ """ user = models.ForeignKey(User, on_delete=models.CASCADE) code = models.CharField(max_length=100) date_expired = models.DateTimeField(default=tomorrow) def __str__(self): return self.code the register in views.py def register(request): if request.method == "GET": form = UserForm() if request.method == "POST": form = UserForm(request.POST) print(vars(form)) if form.is_valid(): user = User.objects.create_user( form.cleaned_data['username'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email=form.cleaned_data['email'], password=form.cleaned_data['password']) user.is_active = False user.save() #create activate code uuid_code = str(uuid.uuid4()).replace("-", '') activate_code = ActivateCode(code=uuid_code) activate_code.save() return HttpResponse(f"You have registered successfully with activate_code: {uuid_code}. \n" "Please activate your account from your registered email.") The error it throwed IntegrityError at /user/register NOT NULL constraint failed: user_activatecode.user_id Request Method: POST Request URL: http://127.0.0.1:8001/user/register Django Version: 1.11.13 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: user_activatecode.user_id How to solve such a problem? -
Django Foreign Key to JSON
I am having hardtime on displaying One field with multiple field (foreign key). Please check the example below for the correct format. Correct format for return example: { "id": 19, "name": "Name here", "email": "zz@zz.zz", "address": "ajot", "note": "ajot", "contact_number": [ "454572", "27", "752752" ] } models.py class PhoneBook(models.Model): name = models.CharField(max_length=50, unique= True) address = models.CharField(max_length=100, default='address') email = models.CharField(max_length=50, default='email') note = models.CharField(max_length=100, default='note') def __str__(self): return self.name class ContactNumber(models.Model): contact_name = models.ForeignKey(PhoneBook, related_name="contact_numbers") contact_number= models.CharField(max_length=30, unique= True) def __str__(self): return self.contact_number views.py def phonebook_detail(request): phonebook_id=request.GET['id'] phonebooklist = PhoneBook.objects.all() data = PhoneBook.objects.get(id=phonebook_id) print(data) #result is combined all contact numbers seperated by comma(,) number_data = ContactNumber.objects.get(contact_name_id=data) return JsonResponse({"message":"success", "id":data.id, "name":data.name, "address":data.address, "email": data.email, "note":data.note, "contact_number": number_data #It should the correct format of contact_number in the example },safe=False) -
How to change max_length of Django's username field
I'm using the default Django User backend. I just want to make one small change: reduce the max_length of username to 30 (I believe the default is 150). How would I achieve this? I'm using django-allauth as my user account framework and here is my current custom allauth signup form: draft1/forms class AllauthSignupForm(forms.Form): captcha = ReCaptchaField( public_key=config("RECAPTCHA_PUBLIC_KEY"), private_key=config("RECAPTCHA_PRIVATE_KEY"), ) class Meta: model = User def signup(self, request, user): """ Required, or else it throws deprecation warnings """ pass draft1/settings.py ACCOUNT_SIGNUP_FORM_CLASS = 'draft1.forms.AllauthSignupForm' Any idea how I can change the username max_length to 30? -
windows python install Wagtail UnicodeDecodeError: 'gbk' Codec Fails to Decode Byte
windows python install Wagtail UnicodeDecodeError: 'gbk' Codec Fails to Decode Byte System environment windows 10 Python3.6.5 Django2.0.6 error info Collecting wagtail Using cached https://files.pythonhosted.org/packages/fe/7e/7f54fa12abad0399247e4dfa00e05aeaa3b7cf80dcab7e8653950878c79e/wagtail-2.1-py3-none-any.whl Requirement already satisfied: beautifulsoup4<5.0,>=4.5.1 in d:\anaconda3\lib\site-packages (from wagtail) (4.6.0) Collecting django-treebeard<5.0,>=4.2.0 (from wagtail) Using cached https://files.pythonhosted.org/packages/14/8a/d3d85018bb14cf951a41f362da1505e0523ff8b798844e270f030d4646ac/django-treebeard-4.3.tar.gz Requirement already satisfied: Django<2.1,>=1.11 in d:\anaconda3\lib\site-packages (from wagtail) (2.0.6) Collecting Willow<1.2,>=1.1 (from wagtail) Using cached https://files.pythonhosted.org/packages/43/de/5dba65cdd859e5bc4e758e5fdb095f5770c9e2ddcc44679bcb54a714925d/Willow-1.1-py2.py3-none-any.whl Collecting draftjs-exporter<3.0,>=2.0 (from wagtail) Using cached https://files.pythonhosted.org/packages/c3/98/2ae0db16e3841d9d0623b1a2248987e1edd037ab7eaa04e45e4fdf18873b/draftjs_exporter-2.1.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "D:\Temp\pip-install-szjmba64\draftjs-exporter\setup.py", line 38, in long_description = f.read() UnicodeDecodeError: 'gbk' codec can't decode byte 0x93 in position 1958: illegal multibyte sequence ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in D:\Temp\pip-install-szjmba64\draftjs-exporter\ -
django.db.utils.OperationalError: (1045:Access denied for user 'root'@'localhost' (using password: NO)
I got error django.db.utils.OperationalError: (1045:Access denied for user 'root'@'localhost' (using password: NO) when I ran python3 manage.py migrate to connect MySql and initial database tables in Mac. MySql version: 8.0 OS: macOS 10.13.4 Python: 3.6 Django: 1.10.3 And it's using pymysql to work with Mysql, I did lots of google and also in stackorverflow, finally I found the solution by my own, just want to share one more solution in stackoverflow, if you also encounter this issue, please try my way in the answer below. -
Why Django does not suggest null=True on string based fields?
Django official documentation does not suggest using null=True on string based fields. [source] I understand that they don't like to have two different no data value. Because of this, Django suggests only use empty string as no data value. But, Why they didn't choose None over "" (empty string)? -
Django-ORM instead of python for loop
Hello Awesome People! Such a simple question, sometimes I used to loop through my models with the python for loop, sometimes this is not good for the performance of a website. I have three 3 models: class A(models.Model): Bs = ManyToManyField(B) class B(models.Model): Cs = ManyToManyField(C) class C(models.Model): name = CharField(max_length=100) If I want to have all the instances of the C related to an instance of A, how will I proceed rather than this python for loop? all_c = [] for b in a_instance.Bs.all(): for c in b.Cs.all(): all_c.append(c) -
Return New FormWizard With Data From Current FormWizard
Currently, I have a basic FormWizard using ModelForm derived forms for its steps. When the user is done, it saves to the database. Instead of redirecting them back to an empty FormWizard, I'd like to render a new instance of the FormWizard, starting back on the first step, but pre-populate specific fields with the information they entered in the initial form. Below is the base functionality: class CustomWizardView(SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'uploads')) instance = None def get_form_instance(self, step): if not self.instance: self.instance = Post() return self.instance def done(self, form_list, **kwargs): self.instance.user = self.request.user self.instance.save() return HttpResponseRedirect('/session-form') And here is how I did it before I realized how large my form needed to be, and that it required FormWizard: class PostFormView(TemplateView): template_name = 'form/form.html' def get(self, request): form = TestPostForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = TestPostForm(request.POST, request.FILES) building_floor_data = 0 department_data = '' if form.is_valid(): post = form.save(commit=False) post.user = request.user building_floor_data = form.cleaned_data['building_floor'] department_data = form.cleaned_data['department'] post.save() # return redirect('form') form = TestPostForm() form.fields['building_floor'].initial = building_floor_data form.fields['department'].initial = department_data return render(request, self.template_name, {'form': form}) I'm very new to Django, so this may be a very obvious leap to make. I'm just not getting it. -
Deal with timedelta () and datetime.now
I'd like to set timedelta for a data model class ActivateCode(models.Model): """ """ user = models.ForeignKey(User, on_delete=models.CASCADE) code = models.CharField(max_length=100) date_expired = models.DateTimeField(default=datetime.now + timedelta(days=1)) It seem not a proper solution because datetime.now is not called but timedetla(days=1) is invoked. How to deal with such an issue? -
Why union of two or more queryset doesn't work perfectly with forms.ModelMultipleChoiceField?
Hello Awesome People! I struggled with this for hours. I have a Form that has a field called learning_programs programs = forms.ModelMultipleChoiceField(queryset=Program.objects.none(), required=False, widget=forms.CheckboxSelectMultiple()) I did not fill in the query set argument directly because I have a few things to do with it in the views like combining the default programs with programs chosen by the user. form = CourseForm(request.POST or None) default_programs = Program.objects.filter(default=True) all_programs = default_programs.union(user.programs.filter(default=False)) So far so good, the queryset works also with the union. I assign the queryset to the form field programs form.fields['programs'].queryset = all_programs if request.method == "POST": if form.is_valid(): programs = form.cleaned_data.get("programs") ''' stuff ''' course.programs.add(*programs) The funny thing here is that even though I do not select any items, programs always received all the queryset, I tried course.programs.clear() before, but it did not work, it's still been assigned by all the programs containing in the queryset argument Round 2: after 1 hour I changed the union to |, and it works all_programs = (default_programs | obj.learning_programs.filter(default=False)).distinct() Does anyone know why it did not work with union(), I do not like doing things I do not understand. union() were supposed to work since it's just a combination of 2 queryset of … -
Django Celery apply_async doesn't work
we're using django 1.10, Celery 4.1.0 I'm trying to use apply_async. This is the task: from celery import Celery app = Celery('my_app', broker='redis://127.0.0.1:6379/2') @app.task def add(x, y): print(str(x+y)) raise status.HTTP_500_INTERNAL_SERVER_ERROR When calling it with 'delay' it runs the 'add' function but doesn't retry: add.delay(4, 4) I tried to run the task with 'apply_async' and 'retry' and 'retry_policy' but it doesn't seem to even run the task: add.apply_async((4, 4), retry=True, retry_policy={ 'max_retries': 3, 'interval_start': 0, 'interval_step': 0.2, 'interval_max': 0.2, } ) Am I missing something? -
Django/DRF app receives AttributeError
I am relatively new to web application development and am trying my hand at using Django. I implemented an API using Django Rest Framework and it seemed to work fine at first. I tried adding some bootstrap to hook up to my frontend (React) and now when I run Django with "python manage.py runserver", I receive an AttributeError. I'm not sure how to go about debugging this error. Below is the full stack trace, my views.py and urls.py for context. Stack Trace Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000000560AAAC488> Traceback (most recent call last): File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\utils\autore load.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\core\managem ent\commands\runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\core\managem ent\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\core\managem ent\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\core\checks\ registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\core\checks\ urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\core\checks\ urls.py", line 23, in check_resolver return check_method() File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\urls\resolve rs.py", line 397, in check for pattern in self.url_patterns: File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\utils\functi onal.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\urls\resolve rs.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\aidancain\envs\usaproject\lib\site-packages\django\utils\functi onal.py", line 36, in … -
I want to get the url of a ForeignKey in Django Rest Framework
I have a HyperlinkedModelSerializer of a model with a ForeignKey, and I want to return the hyperlink to the instance referenced in that field, but I get the whole object nested in the json. These are my models: class Hotel(models.Model): ONE_STAR = '*' TWO_STARS = '**' THREE_STARS = '***' FOUR_STARS = '****' FIVE_STARS = '****' GRAND_TOURISM = 'GRAND_TOURISM' NA = 'NA' SPECIAL = 'SPECIAL' ECO = 'ECO' BOUTIQUE = 'BOUTIQUE' HOTEL_CATEGORY_CHOICES = ( (ONE_STAR, _('*')), (TWO_STARS, _('**')), (THREE_STARS, _('***')), (FOUR_STARS, _('****')), (FIVE_STARS, _('*****')), (GRAND_TOURISM, _('Grand Tourism')), (NA, _('NA')), (SPECIAL, _('Special')), (ECO, _('Eco-Hotel')), (BOUTIQUE, _('Boutique-Hotel')) ) company = models.OneToOneField(Company, on_delete=models.CASCADE, primary_key=True, verbose_name=_('Company')) code = models.CharField(max_length=10, verbose_name=_('Code')) city = models.ForeignKey(City, on_delete=models.PROTECT, related_name='hotels', verbose_name=_('City')) category = models.CharField(max_length=20, choices=HOTEL_CATEGORY_CHOICES, verbose_name=_('Category')) capacity = models.IntegerField(verbose_name=_('Capacity')) position = models.DecimalField(max_digits=11, decimal_places=2, default=0.00, verbose_name=_('Position')) in_pickup = models.BooleanField(default=False, verbose_name=_('In pickup?')) is_active = models.BooleanField(default=True, verbose_name=_('Is active?')) class Meta: verbose_name = _('Hotel') verbose_name_plural = _('Hotels') def __str__(self): return self.company.name class Company(models.Model): name = models.CharField(max_length=40, verbose_name=_('Name')) legal_name = models.CharField(max_length=100, null=True, blank=True, verbose_name=_('Legal name')) tax_id = models.CharField(max_length=12, null=True, blank=True, verbose_name=_('Tax ID')) url = models.URLField(null=True, blank=True, verbose_name=_('URL')) address = models.TextField(max_length=400, null=True, blank=True, verbose_name=_('Address')) class Meta: verbose_name = _('Company') verbose_name_plural = _('Companies') def __str__(self): return "[{}]{}".format(self.id, self.name) This is my serializer: class HotelProductsSerializer(serializers.HyperlinkedModelSerializer): company = CompanySerializer() …