Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Counting in django template
I want to count the numbers series in these templates for eg: in the 1st box, only one object is there S.no is 1, in the second box a lot of objects are there S.no starts from again 1,2,3,--- but I want to show serially], please help me, guys. -
Django authenticate() always return None for a custom model
I'm new to django, and I have to make a back-end with it. my issue: I have multiple models (clients,driver,company) all of them should login and authenticate (each one on a diffrent app, but they all extend the same user model), i have seen so many questions like this, but none of them solved my issue which is authenticate(username='username',password='password') always return none. the user record exists in the DB, i checked it with filter(username=(username). so here is some code: The UserManager class: class UserManager(BaseUserManager): def create_user(self, username, password, phone): if not username: raise ValueError("user must provide a username") if not password: raise ValueError("user must provide a password") if not phone: raise ValueError("user must povide a phone number") user_obj = self.model( user_name=username, phone=phone ) user_obj.set_password(password) user_obj.save() return user_obj the User class: class User(AbstractBaseUser): user_name = models.CharField(max_length=32, unique=True) email = models.EmailField(max_length=255, unique=True, null=True) phone = PhoneNumberField() access_token = models.CharField(max_length=255, unique=True, null=True) notifications_token = models.CharField(max_length=255, unique=True, null=True) photo = models.ImageField() person_in_contact = models.CharField(max_length=32) active = models.BooleanField(default=False) confirmedEmail = models.BooleanField(default=False) confirmedPhone = models.BooleanField(default=False) completedProfile = models.BooleanField(default=False) objects = UserManager() @property def is_active(self): return self.active def __str__(self): return "Client : " + self.user_name + " Email:" + self.email def get_email(self): return self.email USERNAME_FIELD = 'user_name' … -
Django range data with from and to date
I try create to queryset with dates - from=2019.01.01 to 2019.01.02 . And i want output all data who fell into this range with 2019.01.01 and 2019.01.02 inclusive My models: class Commitment(models.Model): scheduled_date = models.DateField() created_date = models.DateTimeField(auto_now_add=True, blank=True) Not work: commitments = Commitment.objects.filter(dealer=dealer, scheduled_date__year=get_next_year(), created__date__gte=self.from_date, created__date__lte=self.to_data) Not work: commitment_query = Q(dealer=dealer) commitment_query.add(Q(scheduled_date__year=get_next_year()), Q.AND) commitment_query.add(Q(created_date__gte=self.from_date), Q.AND) commitment_query.add(Q(created_date__lte=self.to_data), Q.AND) commitments1 = Commitment.objects.filter(commitment_query) Not work: commitments = Commitment.objects.filter(dealer=dealer, scheduled_date__year=get_next_year(), created_date__range=(self.from_date, self.to_data)) -
How to serialize a custom data set of two models in Django Rest Framework
I have a super important query: I want to serialize a set of data, or rather a model that has foreign keys of another model, so that through the foreign key I want to show the field of the other table, like the name: Model Equipos id_equipo=models.PositiveSmallIntegerField(primary_key=True) nombre=models.CharField(max_length=15) vendedor=models.CharField(max_length=10,default='S/A',blank=True) ip_gestion=models.GenericIPAddressField(protocol='Ipv4',default='0.0.0.0') tipo=models.CharField(max_length=8,default='S/A',blank=True) localidad=models.CharField(max_length=5,default='S/A',blank=True) categoria=models.CharField(max_length=10,default='S/A',blank=True) ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table = 'Equipos' Model Interfaces class Interfaces(models.Model): id_interface=models.PositiveIntegerField(primary_key=True) id_EquipoOrigen=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_origen') id_PuertoOrigen=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_origen',null=True,blank=True) estatus=models.BooleanField(default=False) etiqueta_prtg=models.CharField(max_length=80,null=True,blank=True) grupo=models.PositiveSmallIntegerField(default=0,blank=True) if_index=models.PositiveIntegerField(default=0,blank=True) bw=models.PositiveSmallIntegerField(default=0,blank=True) bw_al=models.PositiveSmallIntegerField(default=0,blank=True) id_prtg=models.PositiveSmallIntegerField(default=0,blank=True) ospf=models.BooleanField(default=False) description=models.CharField(max_length=200,null=True,blank=True) id_EquipoDestino=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_destino') id_PuertoDestino=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_destino') ultima_actualizacion=models.DateTimeField(auto_now=True) So I want to create a serializer where, through the Id_EquipoOrigen (which refers to the Equipos model) of the interfaces model, it is able to be able to present in a json the fields nombre, localidad, categoria of the Equipos model. -
UpdateView and DeleteView lead to error 405 when submit is clicked
CreateView loads a form and when submit is clicked it redirects to the detail page of the new object; UpdateView correctly loads the form template already filled with the information about the current object but when submit is clicked to save the updates leads to a 405 blank page and the object is not updated; The same happens with DeleteView: 405 error and the object isn't deleted, the only difference is that DeleteView loads a different template form. It seems a common problem, I found different solutions on similar questions here but none is working for me. I'm stuck from a couple of days so any hint is really appreciated. Since I'm learning I would like to have some explanation about why this occours rather than some code I have to copy/paste. Thanks all. # urls.py app_name = 'articles' urlpatterns = [ path('', ArticleListView.as_view(), name='article-list'), path('create/', ArticleCreateView.as_view(), name='article-create'), path('<int:id>/update', ArticleUpdateView.as_view(), name='article-update'), path('<int:id>/', ArticleDetailView.as_view(), name='article-detail'), path('<int:id>/delete', ArticleDeleteView.as_view(), name='article-delete') #models.py class Article(models.Model): title = models.CharField(max_length=120) content = models.CharField(max_length=255) def get_absolute_url(self): return reverse("articles:article-detail", kwargs={"id": self.id}) # views.py class ArticleListView(ListView): template_name = 'templates/blog/article_list.html' queryset = Article.objects.all() class ArticleDetailView(DetailView): template_name = 'blog/article_detail.html' def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Article, id=id_) class ArticleCreateView(CreateView): template_name = 'blog/article_create.html' … -
Universal API for all models
I am new in python(django) and I wanna do universal api for all models in my app with create update insert and delete. and serializer do not have a data when i use it for create and delete. i want response data when i insert and deleted true or false when i delete it. 2 Question is - Is my code and an approach correct or i do something wrong or not correct? Why i ask? cause i just startwed django/ Thank you from collections import namedtuple import null from django.apps import apps from rest_framework.response import Response from .serializers import * from .models import * from rest_framework import generics, viewsets, status class GeneralViewSet(viewsets.ModelViewSet): myModel = null MyApiObj = null @property def api_object(self): return namedtuple("ApiObject", self.request.data.keys())(*self.request.data.values()) @property def model(self): return apps.get_model(app_label=self.MyApiObj.app, model_name=self.MyApiObj.object) def get_serializer_class(self): GeneralSerializer.Meta.model = self.myModel return GeneralSerializer def post(self, request): self.MyApiObj = self.api_object self.myModel = self.model return self.query_type() def query_type(self): if (self.MyApiObj.query == 'SELECT'): return self.select_api() elif (self.MyApiObj.query == 'INSERT'): return self.insert_api(), elif (self.MyApiObj.query == 'UPDATE'): return self.update_api(), elif (self.MyApiObj.query == 'DELETE'): return self.delete_api(), else: return Response('', status=status.HTTP_400_BAD_REQUEST) # print(self.MyApiObj.query) # query_select = { # 'SELECT': self.select_api(), # 'INSERT': self.insert_api(), # 'UPDATE': self.update_api(), # 'DELETE': self.delete_api(), # } # … -
GraphQL Django Graphene microservices: Weaving Rest API into GraphQL endpoint
We have a Monolith code base that we are slowly breaking down into micro-services. The main code base uses django GraphQL via graphene. One service now is accounts. Each account has a route field with an id. I have managed to get the accounts micro-service REST API back into the main graphQL endpoint with the following code sample: class MicroDeliveryRoutesType(ObjectType): id = graphene.ID() routeName = graphene.String() loadingDay = graphene.Int() class MicroAccountNameType(ObjectType): id = graphene.ID() accountCompanyid = graphene.String() commonName = graphene.String() parentAccountid = graphene.Field(lambda: MicroAccountNameType) routeid = graphene.Field(MicroDeliveryRoutesType) class Query(graphene.ObjectType): list_microAccountNames = graphene.List(MicroAccountNameType) list_microDeliveryRoutes = graphene.List(MicroDeliveryRoutesType) def resolve_list_microAccountNames(self, context, *args, **kwargs): url = 'https://routeToAccounts' data = requests.get(url) return json2obj(json.dumps(json.loads(data.content))) def resolve_list_microDeliveryRoutes(self, context, **kwargs): return json2obj(json.dumps([{"routeName":"Test Route", "id":"1"}])) At the moment ALL the routeid fields for all the accounts (there id's and routeNames) are returning null. I know I am only returning one sample set, but I would expect all the accounts that have a routeid == 1 to at least return id=1 and routeName="Test Route" But like I said all my data basically looks like the data below: { "accountCompanyid ": "P70", "commonName": "Company 70", "id": "1", "routeid": { "routeName": null, "loadingDay": null, "id": null }, "parentAccountid": null } How can … -
how to build sign up user with extra field(dropdown list filled from database) from another table?
i want make sign up for user and i make extends user to another field from antoher model , my three field inr egistration is : username ,password ,structure_designation where the last one is a drop down list getted from database and it is filled in photo you see the model.py can u help me to build views .py and forms.py from django.db import models from django.contrib.auth.models import User from immob.models import Structure from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) structure=models.ForeignKey(Structure, on_delete=models.CASCADE,null=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Auth user Django in another database
In the same project I have some apps that should store data in the localhost database and some in a remote database. I created a routers.py file and imported it into my settings.py. I also defined 2 databases in my settings file. Is this the correct one? On some models/class I set app_label = 'remote_db' where I need to write data to the remote database. part of settings.py DATABASES={ 'default':{ ... }, 'remote_db':{ ... } } DATABASE_ROUTERS = ['smart.routers.AccessRouter',] AUTH_USER_MODEL = 'users.SmartUser' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) part of users/ models.py class SmartUser(AbstractBaseUser, PermissionsMixin): class Meta: app_label = 'remote_db' When i try run makemigrations users i heave the warning/ error: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.SmartUser' that has not been installed -
Can I make the lines thicker on this brushstroke animation I made with an svg in html & css?
I made a svg and animated it to write out my text. I want it to have thick brushstrokes and look similar to this website(http://weaintplastic.com), writing out letters one by one. At the moment it just traces the letters at the same time making it hard to read the word and the lines are very thin. I would like to make the brushstrokes thicker and to animate each letter to write out one at a time with html and css. I created my svg on this website(https://vectr.com/) by using their text function and then sketched the path of each individual letter with the trace tracing each individual letter with the pen tool. I used this link to open the svg https://jakearchibald.github.io/svgomg/ and copied the svg as text. Then I followed the instructions on this website to animate it https://dev.to/oppnheimer/you-too-can-animate-svg-line-animation-jgm. Here's the link to my code https://codepen.io/anon/pen/JgEadZ#anon-signup html with svg path <div id="header"> <div id="content"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="640" height="640"> <defs> <path d="M189.37 447.93l-8.06-17.6-18.94-41.4-17.9 41.76-9.1 21.24" id="a"/> <path d="M259.91 434.47l-.15 7.99-12.14 7.78-26-.48-13.85-8.26-5.63-19.61 12.49-26.27 24.08-4.55 18.82 10.35" id="b"/> <path d="M332.37 436.93l-20 15-20-4-9-11-5-13 5-25 13-10H320l12.37 10" id="c"/> <path d="M402.37 451.93h-47v-63h43" id="d"/> <path d="M398.37 418.43h-43" id="e"/> <path d="M470.46 388.93v61h-7.15l-42.94-61v61" id="f"/> <path d="M538.17 388.93h-53 25v63" … -
Custom Form with Socialaccount in Django-allauth
I'm trying to modify the social account (in my case with Google) sign-up using django-allauth. What I would like to achieve is to have the user click my "Sign-up with Google" button, but after Google login (on the callback) I would like to present the user with a consent form (regarding rules/GDPR) which he needs to submit before finalising the procedure. Here's my form: // landing/forms.py from allauth.socialaccount.forms import SignupForm class GoogleSignUpForm(SignupForm): privacy_policy = forms.BooleanField( required=True, label=_('I accept the privacy policy and rules '), help_text=_('You need to accept this to proceed with setting-up your account') ) def __init__(self, sociallogin=None, **kwargs): super(GoogleSignUpForm, self).__init__(**kwargs) terms_and_conditions = reverse_lazy('privacy') self.fields['privacy_policy'].label = mark_safe(_( "I have read and agree with the " "<a href='%s'>Terms and Conditions</a>")) % ( terms_and_conditions) def save(self): user = super(GoogleSignUpForm, self).save() return user I have the following setting in my base.py setting file: SOCIALACCOUNT_FORMS = {'signup': 'landing.forms.GoogleSignUpForm'} And yet - the import line from allauth.socialaccount.forms import SignupForm is giving me the following error: django.core.exceptions.ImproperlyConfigured: Error importing form class landing.forms: "cannot import name 'BaseSignupForm'" Why is this happening and how to make this work? -
Aggregate in JSONFields in Django
I'm using PostgreSQL and a django model like this: class MyModel(models.Model): click_sources = JSONFields() and sum records like this: 1. click_sources = {"link1": 20, "link2": 40} 2. click_sources = {"link1": 30, "a": 60} 3. click_sources = {"a":3, "blah": 5} My question is about an aggregation query which results from the sum of all keys like this: {"link1": 20, "link2": 40, "a": 63, "blah": 5} -
How to create object within nested serializer on API create call
I have an API with nested serializers where I overwrote the create method. My nested serializer has Foreign Keys to another model. Now I want to create objects of this other model in the same API call. This is where I am stuck. My data looks like so: [ { "project": "project1", "name": "Graph1", "description": "testdescription", "nodes": [ { "id": 16, "name": "target1", "graph": 49 }, { "id": 15, "name": "Node1", "graph": 49 } ], "edges": [ { "id": 14, "name": "Edge1", "graph": 49, "source": 15, "target": 16 } ] } ] The fields source and target are Foreign Keys to the model Node. Now, I can send this data without a problem when the fields source and target are already existent in the database. But what I want is, that I send the data and I create a new Node object (source) and a new Node object (target) in the same call. So far I overwrote the create method to enable nested serialization like so: class GraphSerializer(serializers.ModelSerializer): nodes = NodeSerializer(many=True) edges = EdgeSerializer(many=True) class Meta: model = Graph fields = ('project', 'name', 'description', 'nodes', 'edges', ) def create(self, validated_data): nodes_data = validated_data.pop('nodes') edges_data = validated_data.pop('edges') graph = Graph.objects.create(**validated_data) for … -
django-intl-tel-input returns 404 error in the terminal?
I'm using Django-intl-tel-input to make a widget in the user sign up page to choose the phone number format/country but the widget doesn't appear in the page and the terminal gives the following error : Not Found: /accounts/signup/”https: //code.jquery.com/ui/1.12.1/jquery-ui.js” Not Found: /accounts/signup/”https://code.jquery.com/jquery-1.12.4.js” Not Found: /accounts/signup/<link href= [29/Jul/2019 14:10:52] "GET /accounts/signup/%E2%80%9Dhttps://code.jquery.com/jquery-1.12.4.js%E2%80%9D HTTP/1.1" 404 5475 Not Found: /accounts/signup/<script type= [29/Jul/2019 14:10:52] "GET /accounts/signup/%E2%80%9Dhttps://code.jquery.com/ui/1.12.1/jquery-ui.js%E2%80%9D HTTP/1.1" 404 5493 [29/Jul/2019 14:10:52] "GET /accounts/signup/%3Clink%20href= HTTP/1.1" 404 5370 [29/Jul/2019 14:10:52] "GET /accounts/signup/%3Cscript%20type= HTTP/1.1" 404 5376 Not Found: /accounts/signup/”https://code.jquery.com/jquery-1.12.4.js” [29/Jul/2019 14:10:53] "GET /accounts/signup/%E2%80%9Dhttps://code.jquery.com/jquery-1.12.4.js%E2%80%9D HTTP/1.1" 404 5475 Not Found: /accounts/signup/”https://code.jquery.com/ui/1.12.1/jquery-ui.js” [29/Jul/2019 14:10:53] "GET /accounts/signup/%E2%80%9Dhttps://code.jquery.com/ui/1.12.1/jquery -ui.js%E2%80%9D HTTP/1.1" 404 5493 I didn't load/call any CSS or js files in this template {%load staticfiles %} {% block content %} <head>> <link href="{{ form.media.css }}" rel="stylesheet"> </head> <style> #content{ margin-top : 4%; margin-left : 18%; margin-right : 2%; margin-bottom : 6%; } </style> <div id="content"> <h2>Sign up</h2> <form method="POST" action="{% url 'accounts:signup' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Sign up</button> <p></p> </form> </div> <script src="{{ form.media.js }}"></script> <script> jQuery(document).ready( {{ form.media.js }} ); </script> {% endblock %} and my form : class SignupForm(UserCreationForm): Telephone_num = forms.CharField(label='Phone Number', widget= IntlTelInputWidget()) class Meta(UserCreationForm.Meta): model = MyUser fields = ('first_name', 'last_name', 'email', … -
Validation error on empty forms using CreateView and modelformset
I use forms and want to avoid filling out all forms on the page, but my code only works if all forms are filled in. If I send some forms empty, I get an error The view base.views.SkillTestCreateView didn't return an HttpResponse object. It returned None instead. views.py class SkillTestCreateView(AuthorizedMixin, CreateView): model = Skill form_class = SkillCreateForm template_name = 'skill_create.html' def get_context_data(self, **kwargs): context = super(SkillTestCreateView, self).get_context_data(**kwargs) context['formset_framework'] = SkillFrameworkFormSet() context['formset_planguage'] = SkillPLanguageFormSet() return context def post(self, request, *args, **kwargs): if 'framework' in request.POST: form = SkillFrameworkFormSet(self.request.POST) if form.is_valid(): return self.form_valid(form) elif 'language' in request.POST: form = SkillPLanguageFormSet(self.request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(self.form) def form_valid(self, form): """If the form is valid, redirect to the supplied URL.""" print('valod') for form in form: self.object = form.save(commit=False) self.object.employee =Employee.objects.get(pk=self.kwargs['pk']) self.object.save() return redirect("profile", pk=self.kwargs['pk']) def form_invalid(self, form): print('Invalid') return self.render_to_response(self.get_context_data(formset_framework=self.form, formset_planguage=self.form)) How do I allow acceptance of empty forms? -
Django - How To Use Form In Footer
Previously, I had my 'subscribe to newsletter' form on the home page (index.html). However, I moved it to the footer.html in order for it to be shown on every page. The issue is that since the logic to deal with the form is only in the home view, submitting to the form only works on the home page. Here is some code to help you understand: This is in footer.html which is included in base.html which is extended by all other htmls <form class="nwsltr-primary-1" action="." method="POST"> <!-- . means current URL we are on --> {% csrf_token %} <input type="email" name="email" id="email" placeholder="Your email"/> <button type="submit"><i class="ion-ios-paperplane"></i></button> </form> This is what I think needs to change. This is the view for the home page and the only place the logic for the form is being seen: def index(request): # featured and object_list get all Posts with featured bool true. order_by=latest first. :6=first 6 featured = Post.objects.filter(featured=True).order_by('-share_count')[:6] latest = Post.objects.order_by('-timestamp')[:5] popular = Post.objects.order_by("-share_count")[:4] # Basic but does not do any verification if request.method == "POST": email = request.POST["email"] new_signup = Signup() new_signup.email = email new_signup.save() context = { 'object_list': featured, 'latest': latest, 'popular': popular } return render(request, 'index.html', context) # html … -
Circular dependency created by serializer
When importing a serializer into my model the model cannot be imported anymore so I suspect there is a circular dependency. When not importing the serializer everything goes smoothly but when importing it everything breaks. This works from shift.models import Shift class ShiftChangeRequest(models.Model): shift = models.ForeignKey(Shift, on_delete=models.CASCADE, null=True) And this does not: from shift.models import Shift from shift.serializers.base import BaseSerializer class ShiftChangeRequest(models.Model): shift = models.ForeignKey(Shift, on_delete=models.CASCADE, null=True) As you can see the ShiftChangeRequest does have a connection with shift but in the BaseSerializer ShiftChangeRequest is not even mentioned: from rest_framework import serializers from shift import models class BaseSerializer(serializers.ModelSerializer): class Meta: model = models.Shift fields = [ "id", "title", "start", "end", "amount_of_minutes", "amount_of_employees", "client", "skills", "users", "repeat_at", ] I expected that everything worked as before the import but I get the error ImportError: cannot import name 'ShiftChangeRequest' -
How to exclude the field which it is the foreign key to the parent model
How can I exclude the credit field from CreditInlineAdmin. In this case I get error: : (admin.E201) Cannot exclude the field 'credit', because it is the foreign key to the parent model 'credits.Credit'. models.py class AbstractBaseAction(models.Model): name = models.CharField(_('name'), max_length=255) short_description = models.CharField(_('short description'), max_length=255) full_description = models.TextField(_('full description'), blank=True, null=True) class Meta: abstract = True class CreditAction(AbstractBaseAction): credit = models.ForeignKey(Credit, verbose_name=_('credit')) admin.py class BaseActionInlineAdmin(admin.StackedInline): model = AbstractBaseAction extra = 0 max_num = 2 class CreditActionInlineAdmin(BaseActionInlineAdmin): exclude = ('credit',) model = CreditAction class CreditAdmin(BaseCreditAdmin): inlines = [CreditActionInlineAdmin] -
Django 2 Saving models.FileField manualy in forms.py
My code is: Models.py class Claimmessage(models.Model): text = models.TextField(_('Сообщение'),) class Claimfile(models.Model): claimmessage = models.ForeignKey(Claimmessage, on_delete=models.CASCADE, verbose_name=_('Сообщение рекламации'), ) attachment = models.FileField(upload_to='claims/%Y/%m/%d/', blank=True, null=True,) forms.py class ClaimCreateForm( forms.Form ): message = forms.CharField(widget=forms.Textarea,) attachments = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) def save(self, commit=False): message = self.cleaned_data.get("message") attachments = self.cleaned_data.get("attachments") mess = Claimmessage() mess.text = message mess.save() for f in attachments: Claimfile. objects.create(claimmessage=message, attachment=f) views.py if request.method == 'POST': form = ClaimCreateForm(request.POST, request.FILES,) if form.is_valid(): obj = form.save() return redirect('claim_details', claim_id=obj.pk) else: form = ClaimCreateForm() And I ve got AttributeError at /ru/claims/400002013/create/ 'bytes' object has no attribute '_committed' How can I save file object in form.save() method? -
Use autocomplete_fields with Proxy model
I want to implement autocomplete_fields feature but it doesn't work. I assume it happens because of Proxy model. So I have Customer Proxy model and PromoCode model. PromoCode has FK to Customer model. And I need to have search field for customers in PromoCode change form. Here are models and admin classes: class User(AbstractUser): # bunch of fields class Customer(User): class Meta: proxy = True class CustomerAdmin(admin.ModelAdmin): search_fields = ['email',] admin.site.register(Customer, CustomerAdmin) class PromoCode(TimeStampedModel): customer = models.ForeignKey(User, on_delete=PROTECT, null=True, blank=True) class PromoCodeAdmin(admin.ModelAdmin): autocomplete_fields = ('customer',) admin.site.register(PromoCode, PromoCodeAdmin) This code gives error: : (admin.E039) An admin for model "User" has to be registered to be referenced by PromoCodeAdmin.autocomplete_fields. But I can't change model in customer field to Customer, becase when I run migration it breaks with following error: ValueError: The field coupons.PromoCode.customer was declared with a lazy reference to 'users.customer', but app 'users' doesn't provide model 'customer' Also I can't register User as admin class, because I don't need it to be registered. I register Customer model. What can I do to solve such case? -
Django : null value in column "id" violates not-null constraint(Issue is at admin)
On addidng the data from admin panel in django , on adding the records , the postgresql is throwing the error as primary key is getting the null value.As it must be auto incremented. Please let me know how to fix this issue and why it may be persisting . As previously , this issue got fixed automatically. -
Getting Bad request 400 when testing API create method
I am trying to test an API with pytest. I am getting a bad request 400 where I'd expect a status code 201. There must be some error in how I set up the test data but I can't figure out where. this is the data I am trying to send graph_data = { "project": "project1", "name": "Graph1", "nodes": [ { "name": "Node1 of Graph 1", "graph": 1 } ], "edges": [ { "name": "EdgeForGraph1", "graph": 1, "source": 1, "target": 1 } ] } And here my test: @pytest.mark.django_db class TestCreate: def setup(self): """Setup for tests to create user, graph, project and node """ password = 'mypassword' username = 'testuser' project = Project.objects.create(project_name='project1') graph = Graph.objects.create(project=project, name='Graph1') node = Node.objects.create(graph=graph, name='node of Graph') source = Node.objects.create(graph=graph) target = Node.objects.create(graph=graph) user = User.objects.create_superuser(username=username, email='test@test.com', password=password) edge = Edge.objects.create(graph=graph, source=source, target=target) def test_aut_user_can_create_graph(self, client): headers = get_token(client) print(headers) create_data = graph_data print(create_data) url = api_reverse('create-graph') response = client.post(url, create_data, headers=headers) assert response.status_code == 201 the get_token method returns a token that I use to authenticate. Here are my models: class Graph(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=120, blank=True) description = models.CharField(max_length=400, blank=True) def __str__(self): return self.name @property def nodes(self): return self.node_set.all() … -
multilingual site: how create clean relationship between "static" texts (coded into templates) and database?
On a multilingual (manually translated) website appropriate translations of products or newspaper-articles are pulled out according to user (or user-selected) language. But what about all those annoying "static" texts that ordinarily get coded directly into a template? Perhaps "opening hours" or "contact us"? Obviously these need to exist in various translations (and therefore in the database), my question is how to develop clearly the relationship between database entry and code? So far was thinking of the following: MODELS Language name Article article_title article_slug Translation article =models.ForeignKey(Article) language =models.ForeignKey(Language) title_text article_text VIEWS def page12view(request) article = article.objects.get(slug=friendly-name-of-article) query = Translation.objects.filter(article=article).filter(language=request.user.language) if not query.first(): #if translation not available in user’s language default to ENGLISH (pk=1) query = Translation.objects.filter(article=article).filter(language=1) context = { ‘friendly-name-of-article’: query.first()} return render (request,’page12.html', context) TEMPLATE {{friendly-name-of-article.title_text}} {{friendly-name-of-article.article_text}} The idea revolves around giving each article a slug (referred to in above example as "friendly-name-of-article"). Thus "about-us", "opening-hours"etc.. That string would be copy-pasted in the view and template as suggested in the code. The idea is that it would at least bring some clarity as to what is going on. But is it a good idea? Have my doubts... Any good practices to share? -
nginx upstream prematurely closed connection on Django on the server
I have a Django 2.x application and separated API and admin urls using Django_hosts plugin. I have the following nginx configuration to serve the two URLs upstream app_server { server localhost:8000; } server { listen 80; server_name api.staging.example.io admin.staging.example.io; access_log /etc/nginx/log/local-wc.access.log; error_log /etc/nginx/log/local-wc.error.log; location / { proxy_http_version 1.1; proxy_pass http://app_server/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Protocol $scheme; proxy_temp_file_write_size 64k; proxy_connect_timeout 10080s; proxy_send_timeout 10080; proxy_read_timeout 10080; proxy_buffer_size 64k; proxy_buffers 16 32k; proxy_busy_buffers_size 64k; proxy_request_buffering off; proxy_buffering off; } listen 443 ssl; # managed by Certbot ssl_certificate ... } I have configured boto3 to upload files to S3 using django-storages plugin. When I visit htts://admin.staging.example.com and create a model record and uploads the file, the file is being saved to S3 bucket but within a few seconds the gives 502 page. The nginx error log have [error] 9566#9566: *1 upstream prematurely closed connection while reading response header from upstream, client: 13.233.000.90, server: api.staging.example.io, request: "POST /myapp/view/add/ HTTP/1.1", upstream: "http://127.0.0.1:8000/myapp/view/add/", host: "admin.staging.example.io", referrer: "https://admin.staging.example.io/myapp/view/add/" I tried configurations from the other answers with a similar title but none of them is working. Creating an object without uploading file is working fine. -
Display Algolia Results with Jinja / Django
I have got Algolia all set up with Django and the results are displaying. However, when I move on to formatting them there is a clash with the Jinja templating engine. Essentially Algolia uses the double parentheses like Jinja {{ value }} In the script below the {{ highlightResult.name }} cause a error How do I render the results of the search without using the double parentheses? Thanks! <script> const searchClient = algoliasearch('xxx', 'xxx'); const search = instantsearch({ indexName: 'Item', searchClient, }); console.log(search) search.addWidget( instantsearch.widgets.searchBox({ container: '#searchbox', }) ); search.addWidget( instantsearch.widgets.hits({ container: '#hits', templates: { item: ` <div> {{ highlightResult.name }} </div> `, }, }) ); search.start(); </script>