Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
validate and handle error to pass meaningful status back to client
I am using graphene-django instead of rest api(rest framework). I am working on user registration. In the rest framework, validation was done in serializers part but when using graphene how do i validate and handle error for passing meaningful status to client? Here is the registration code class Register(graphene.Mutation): class Arguments: email = graphene.String(required=True) password = graphene.String(required=True) password_repeat = graphene.String(required=True) user = graphene.Field(UserQuery) success = graphene.Boolean() errors = graphene.List(graphene.String) @staticmethod def mutate(self, info, email, password, password_repeat): if password == password_repeat: try: user = User.objects.create(email=email) user.set_password(password) user.is_active = False user.full_clean() user.save() return Register(success=True, user=user) except ValidationError as e: import pdb pdb.set_trace() return Register(success=False, errors=[e]) return Register(success=False, errors=['password', 'password is not matching']) one example can be validation for if user with email already exists -
Image are not displayed in my home page from model.py
I have created a form for user to post their stuff, all other stuff works fine only image can't be displayed in my home page I have tried to overlook again and again the code seems to ok, my guess is the structure of folders of image. Am not really sure how to structure the folders for images. Please help!! views.py @login_required def PostNew(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('loststuffapp:IndexView') else: form = PostForm() return render(request, 'loststuffapp/form.html', {'form': form}) models.py class Documents(models.Model): docs_name = models.CharField(max_length=200,verbose_name="Names in Documents") item_type = models.CharField(default="", max_length=100,verbose_name="Item type" ) police_station = models.CharField(max_length=255, verbose_name="Police station") phone_no = models.CharField(verbose_name="Phone number", max_length=10, blank=False, validators=[int_list_validator(sep=''),MinLengthValidator(10),], default='0766000000') date = models.DateTimeField(default=timezone.now,verbose_name="Date") Description = models.TextField(blank=True, null=True,verbose_name="Description") pay_no = models.IntegerField(default=0,verbose_name="payment number") publish = models.BooleanField(default=False) image = models.ImageField(default="add Item image", upload_to="media",blank=False, verbose_name="Images") """docstring for Documents""" def __str__(self): return self.docs_name forms.py class PostForm(forms.ModelForm): class Meta: model = Documents fields = ['docs_name', 'item_type', 'police_station','phone_no', 'Description', 'image'] labels = {'docs_name': 'Name in Documents','item_type':'Item type','police_station':'Police station', 'phone_no':'Phone number','Description':'Description','image':'Images' } setting.py STATIC_URL = '/static/' MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'loststuff/media') home.html {% for Doc in documents %} <div class="content-wrapper"> <div class="card"> <div class="card-image"> <p><label style="font-size:15px; font-weight: bold;color: black;">Names in … -
Recommended way to render a form with radio button in each row
I want to build a form with a table in which each row contains a radio button and some additional information. Suppose I have two related models: class City(models.Model): name = models.CharField(...) state = models.CharField(...) class Business(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, null=True) I want to create a table showing all rows from the City model with a radio button in the first row, to be saved as the city field in a Business model instance. The additional columns in the table should not be editable. Each row in the table would look something like this: <tr> <td> <input type="radio" name="city_radio"/> </td> <td>CITY NAME HERE</td> <td>CITY STATE HERE</td> </tr> My first thought was to use a ModelFormSet and create a ModelForm representing each row: class CityTableRowForm(forms.ModelForm): city_radio = forms.RadioSelect() class Meta: model = City fields = ['name', 'state'] And use it in the template as such: {% for form in cities_formset %} <tr> <td> {{ form.city_radio }} </td> <td>{{ city.instance.name }}</td> <td>{{ city.instance.state }}</td> </tr> {% endfor %} The table does get rendered correctly. The problem is, each radio gets a different name and so they behave independently from each other. My second approach was to create a ModelForm representing the … -
Always getting 401 or 500 when authenticating users with amazon application load balancer and django oidc provider at receiving access token
I cannot get ALB to check the /userinfo endpoint after receiving access_token, refresh_token and id_token to it I'm trying to authenticate users with Amazon ALB and django_odic_provider. I have set the load balancer authentication on ALB side, tested all oidc endpoints (all are accessible and returning valid results). When I try to authenticate I'm presented with django's login view, I successfully authenticate, but on return from django's oidc/authorize endpoint I get 401 Unauthorized on oauth2/idpresponse page of load balancer. If I try to use Cognito and federated django_oidc_provider I also successfully log in and on return from authorize to oauth2/idpresponse I'm getting 500 server error with message: Exception processing authorization code. It seems to me that ALB is not able to read my response but when I check it everything is formatted as in documentation and jwt is ok. By looking at logs it seems that load balancer never checks token and userinfo endpoints once it receives access_token, refresh_token and it_token from authorization endpoint. I would like to understand how load balancer interprets this response in order to try to figure out what is wrong with it. This is authorization response: { 'access_token': 'd90623245e474ee0b23a0a9ca062ba74', 'refresh_token': '4d439d3249e64cbe9975310f84431c25', 'token_type': 'Bearer', 'expires_in': 3600, … -
djang admin client not making post request properly
I'm trying to make a post request with pytest admin client @pytest.mark.django_db def test_organisation_upload(admin_client): resp = admin_client.post("/mypage/upload_organisations/", follow=True) import pdb; pdb.set_trace() print(resp.content) assert resp.status_code == 201 I have a form in /mypage. When submitting the form, the user is directed to /mypage/upload_organisations/ Problem is, the response being returned is the page itself -- not the result that should be shown upon successful upload. how do i fix this? I want it to actually upload the form, not just go to the page. Everything works fine when i use a request factory (rf) instead. -
Calling a PL/SQL procedure from django with callproc
I need to call a procedure in PL/SQL from an API in Django. I use the callproc and the right values, but get the error: "PLS-00306: wrong number or types of arguments in call" In Oracle I have: PROCEDURE new_payment(pv_id IN VARCHAR2, parr_user IN OWA.vc_arr, parr_date_reg IN OWA.vc_arr, parr_d_value IN OWA.vc_arr, parr_descr IN OWA.vc_arr, parr_type IN OWA.vc_arr, pi_gerar_ref_mb IN PLS_INTEGER DEFAULT 0, pv_data_limite_ref_mb IN VARCHAR2 DEFAULT NULL) In models.py I have: class PAYMENT(): def new_payment(self, id, user, date_reg, value, descr, type): cur = connection.cursor() ref = cur.callproc("PAYMENT.new_payment", [id, user, date_reg, value, descr, type]) cursor.close() return ref In views.py: `pay=PAYMENT() x=pay.new_payment('123', '111', '2019-07-23', '10', 'test1', 'teste2`) At this point, i get the error: `"ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'NEW_PAYMENT'"` Any tip in what am I doing wrong? -
Python Django - update booleanField via List View
Is there any way how to update booleanField in the list view? In list view I have listed all my orders and I need to mark which are done and which are not done. I know I can update it via UpdateView, but that is not user friendly because I have to leave the listview page. models.py class Order(models.Model): ... order = models.CharField(max_length = 255) completed = models.BooleanField(blank=True, default=False) views.py class OrderIndex(generic.ListView): template_name = "mypage.html" context_object_name = "orders" def get_queryset(self): return Order.objects.all().order_by("-id") mypage.html {% extends "base.html" %} {% block content %} {% for order in orders%} User: {{ order.user}} | Completed: {{order.completed}} <input type="checkbox"> {% endfor %} <input type="submit"> {% endblock %} I am quite new to the django framework and have no idea how to make it work. -
$group aggregation with $sum returns nothing
I have a query which runs as expected when it's directly executed in MongoDB, but I'm facing some troubles trying to make it work through MongoEngine. In fact, it returns nothing. Query on MongoDB (which works correctly): db.annual_account.aggregate([{ $group: { "_id":"$adress.city", "total"{$sum: 1} }} ]) Result (which is what I expect): { "_id" : "Genk", "total" : 1 } { "_id" : "Ottignies-Louvain-la-Neuve", "total" : 1 } { "_id" : "Ganshoren", "total" : 1 } { "_id" : "Mont-de-l'Enclus", "total" : 1 } { "_id" : "Charleroi", "total" : 1 } And now, my query on MongoEngine in my views.py: class StatisticsView(generics.ListAPIView): serializer_class = AnnualAccountSerializer def get_queryset(self): group = {"$group" : {"_id": "$code", "total": {"$sum":1} } } response = AnnualAccount.objects.aggregate(group) return response Results: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ {}, {}, {}, {}, {}, ] Does someone has any idea of what is wrong, please? Why I don't have the same result between the shell Mongo and MongoEngine? Thank you, Simon -
HINT: Perhaps you meant to reference the column
When I open the page, I get error: column user_landings_landing.flow_chatbot_id does not exist LINE 1: ...ding"."message", "user_landings_landing"."video", "user_land... ^ HINT: Perhaps you meant to reference the column "user_landings_landing.flow_chatbot". How can I fix it? I tried ` SELECT "flow_chatbot" FROM user_landings_landing; and SELECT flow_chatbot FROM user_landings_landing; but it's not efficiency. -
How to save custom added field in an extended user creation form in django
I am pretty new to Django and i made a custom signup form by extending the UserCreationForms in Django. class SignUpForm(UserCreationForm): #This class will be used in views of account to make sigupform user_type = forms.CharField(required=True,widget=forms.Select(choices=usertypes)) email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ['username', 'user_type','email','password1','password2'] def save(self,commit=True): user = super(SignUpForm, self).save(commit=False) user.user_type = self.cleaned_data['user_type'] print('Flag3') if commit: user.save() return user It is working fine with the view : def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) print('Flag0') if form.is_valid(): user = form.save() if user.user_type == 'Seller' or user.user_type=='seller': print('Flag1') auth_login(request, user) print('Flag2') print(user.user_type) group = Group.objects.get(name='Seller') print(group.name) print('Flag3') user.groups.add(group) return redirect('get_seller') if user.user_type == 'Customer' or user.user_type=='customer': print('Flag1') auth_login(request, user) print('Flag2') print(user.user_type) group = Group.objects.get(name='Customer') print(group.name) print('Flag3') user.groups.add(group) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) I added flags because is was checking the progress of the form. The problem that i am facing is that i want to save the custom field that made user_type . I don't know how to save the custom field or if it is being saved how to get the value. -
I need to do a form that changes on-the-fly depending of a choice
The form that I need to do is for the user to select a payment type.The problem is that depending on the choice if the user wants to pay monthly or annually a different date-picker field has to appear. if he selects monthly, he has to choose a day of the month. And if he chooses annually a date-picker that allows him to pick the month has to appear. I've been searching online for an answer but all I can find is dynamic form in the sense that it can generate a field type multiples times and that is not what I need. All help is appreciated. -
problem with modelchoicefield show objet 1 and object 2without names?
hi friends i have model structure with code and names (structure_desig) i want show list of choices in modelchoicefield and it shows like this structure: --------------------- structure object(1) structure object (2) and i want show name of structure not like that from django.db import models # Create your models here. class Structure(models.Model): structure_code=models.CharField(max_length=1) structure_desig=models.CharField(max_length=350) def __str__(self): return self.structure_desig class Service(models.Model): structure_id= models.ForeignKey(Structure,on_delete=models.CASCADE,null=True) service_desig=models.CharField(max_length=350) class Immob(models.Model): immo_code=models.CharField(max_length=7) immo_desig=models.CharField(max_length=150) immo_qte=models.FloatField(default=1) immo_datemes=models.DateTimeField() immo_cptimmob=models.CharField(max_length=10) immo_dureevie=models.IntegerField(default=7) immo_numaut=models.CharField(max_length=4) immo_origine=models.CharField(max_length=1) immo_fournisseur=models.CharField(max_length=150) immo_nufact=models.CharField(max_length=20) immo_datefact=models.DateTimeField() immo_valht=models.DecimalField(max_digits=18,decimal_places=2) immo_monaie=models.CharField(max_length=3) immo_tauxcvt=models.DecimalField(max_digits=18,decimal_places=2) immo_tauxctrval=models.DecimalField(max_digits=18,decimal_places=2) immo_frais=models.DecimalField(max_digits=18,decimal_places=2) immo_coutacq=models.DecimalField(max_digits=18,decimal_places=2) immo_refcmde=models.CharField(max_length=35) immo_datecmde=models.DateField() immo_journee=models.CharField(max_length=10) immo_cptanal=models.CharField(max_length=9) immo_local=models.CharField(max_length=45) immo_mode_amort=models.CharField(max_length=1) immo_code_r=models.CharField(max_length=2) immo_val_amort=models.DecimalField(max_digits=18,decimal_places=2) immo_status=models.CharField(max_length=1) immo_code_bar=models.CharField(max_length=25) service_id= models.ForeignKey(Service,on_delete=models.CASCADE,null=True) #this is the forms.py from django.contrib.auth.forms import AuthenticationForm from immob.models import Structure from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs= {'class':'form-control'})) password = forms.CharField(widget=forms.PasswordInput(attrs= {'class':'form-control'})) class UserRegistrationForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) structure = forms.ModelChoiceField(Structure.objects.all(), to_field_name="structure_desig") the result it shows like that without names of structure structure: --------------------- structure object(1) structure object (2) and i want show name of structure not like that -
Django how to handle urls.py with a login form in a navbar
I have a login form in a navbar accesible via context processors, I want it to be shown in every page where there's no active user. core/context_processors.py def login_form(request): form = AuthenticationForm() return { 'auth_form': form } The urls.py is stated as normal core/urls.py path('accounts/', include('django.contrib.auth.urls')), And the form in the navbar is called this way: <h2>Login</h2> <form method="post" action="{% url 'login' %}"> {% csrf_token %} {{ auth_form | crispy }} <input type="submit" class="btn btn-primary" value="Login"/> <p><a href="{% url 'password_reset' %}">Lost password?</a></p> </form> Now I don't want a custom login view, since it's available in all templates. But when I hit login I got redirected to a 404 or the login template if a create one. How can I bypass the template part, login the user and redirect somewhere else? -
Django, psycopg2: permission denied on Heroku server
I have a Django project running on Heroku, every time an action is carried out, I get a looong series of errors like this, all pointing back to the same cause: ERROR:django.request:Internal Server Error: /event/ Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: permission denied for relation django_session The URL /event/ does not exist on my project, nor is it referenced anywhere in it, and as far as I know there isn't a database associated with this slackbot (so if someone could also direct me as to how to list all existing databases I would be grateful). How can I fix this through Heroku? I tried the online console with some basic psql command, but all I got was this response psql: could not connect to server: No such file or directory -
django multiple annotate sum advanced
I Have the following queryset, and I want to multiple sum using django annotating but i have some error, Could you please have your suggestions on this??, any help will be appreciated. i already try this but not same what i want myqueryset= BuildingCell.objects.filter(absent__publish='2019-07-22', absent__building_name='f2', absent__bagian='CUT', inputcutsew__publish='2019-07-22', inputcutsew__days='normal', inputcutsew__user=factory_user_cutting)\ .exclude(inputcutsew__cell_name__isnull=True).exclude(inputcutsew__cell_name__exact='').order_by('inputcutsew__cell').values('inputcutsew__cell', 'inputcutsew__model', 'absent__normal_mp', 'absent__ot0_mp', 'absent__ot1_mp', 'absent__ot2_mp', 'absent__ot3_mp').exclude(occult_cell='yes')\ .annotate(total_output_jam=Coalesce(Sum(Case(When(inputcutsew__dummy_days='normal', then='inputcutsew__output'))), 0), total_output_ot=Coalesce(Sum(Case(When(inputcutsew__dummy_days='overtime', then='inputcutsew__output'))),0), total_time=Coalesce(Sum('inputcutsew__time'),0), total_time_ot=Coalesce(Sum('inputcutsew__time_ot'),0), total_time_ot1=Coalesce(Sum('inputcutsew__time_ot1'),0), total_time_ot2=Coalesce(Sum('inputcutsew__time_ot2'),0), total_time_ot3=Coalesce(Sum('inputcutsew__time_ot3'),0))\ .annotate( normal_wmh=Coalesce(F('absent__normal_mp'),0)*Coalesce(F('total_time'),0), normal_swmh=Coalesce(F('absent__normal_mp'),0)*Coalesce(F('total_time'),0), overtime_wmh=(Coalesce(F('absent__ot0_mp'),0)*Coalesce(F('total_time_ot'),0))+(Coalesce(F('absent__ot1_mp'),0)*Coalesce(F('total_time_ot1'),0))+(Coalesce(F('absent__ot2_mp'),0)*Coalesce(F('total_time_ot2'),0))+(Coalesce(F('absent__ot3_mp'),0)*Coalesce(F('total_time_ot3'),0)), overtime_swmh=(1.5*Coalesce(F('absent__ot0_mp'), 0) * Coalesce(F('total_time_ot'), 0)) + (2*Coalesce(F('absent__ot1_mp'), 0) * Coalesce(F('total_time_ot1'), 0)) + (2*Coalesce(F('absent__ot2_mp'), 0) * Coalesce(F('total_time_ot2'), 0)) + (2*Coalesce(F('absent__ot3_mp'), 0) * Coalesce(F('total_time_ot3'), 0)))\ .annotate( sum_total_output_jam=Sum(F('total_output_jam')), sum_total_output_ot=Sum(F('total_output_ot')), sum_overtime_wmh=Sum(F('overtime_wmh')), sum_overtime_swmh=Sum(F('overtime_swmh')) ) FieldError at /superuser/inputtime/2/3/f2/CUT/2019-07-22 Cannot compute Sum('total_output_jam'): 'total_output_jam' is an aggregate -
How to fix: "Unknow command: manage.py" in a Django project in PyCharm (newbie)
I'm totally new to Django, just learned a bit Python for science analysis. I use PyCharm as IDE wanted to made the django "tutorial" from the PyCharm website (https://www.jetbrains.com/help/pycharm/creating-and-running-your-first-django-project.html). I struggle quite early at the point "Launching Django Server". So, I can open the new command line with Ctrl+Alt+R, but when I enter "manage.py" as described in the tutorial I get the error "Unknown command: manage.py Type'manage.py help' for usage". If I type 'manage.py help' the same error occurs. Since PyCharm creates the files, the code itself should be functional since I didn't changed a single line. The versions are: PyCharm 2019.1.3 (Professional); Python: 3.7; Django: 2.2.3 I tried to run PyCharm as administrator. Since I'm totally new to Django I also have no idea what else I should try. A google search showed just findings not comparable to mine. -
How to display and hstore field in forms as separate fields in django
I trying to create a form that separates the hstore field address into fields street, city, state, and zipcode in form.py. But when the form is submitted, it will be added to the database as Hstorefield with {'street':street,'city':city,'state':state,'zipcode':zipcode}. Any help is appreciated! model.py from django.contrib.postgres.fields import HStoreField class Student(models.Model): user=models.OneToOneField(CustomUser,on_delete=models.CASCADE,primary_key=True,) fullname=models.CharField(max_length=100,null=False,blank=False,default="fullname") address=HStoreField(null=True) form.py class StudentProfileForm(forms.ModelForm): street=forms.CharField(max_length=80, required=True, strip=True) city=forms.CharField(max_length=50, required=True, strip=True) state=forms.CharField(max_length=20, required=True, strip=True) zipcode=forms.IntegerField(required=True) class Meta: model = Student exclude = ['user'] # I've tried adding this, but that does nothing to the database. def clean(self): self.cleaned_data['address'] = {"street":self.cleaned_data.get('street'),"city": self.cleaned_data.get('city'), "state": self.cleaned_data.get('state'),"zipcode":self.cleaned_data.get('zipcode'),}, self.save() -
Get data related to manytomany field
I have two model, first one is Industries, second one is experts. My models looks like this. name = models.CharField(max_length=255, verbose_name="Industry name") slug = models.SlugField(unique=True, blank=True, max_length=150) class Expert(models.Model): name = models.CharField(max_length=255, blank=True, verbose_name="Expert Name") industry = models.ManyToManyField(Industries, blank=True, verbose_name="Industries") on the all experts page I made an industries field clickable, when user clicked any industry, My goal is show the experts which is in this industry. My urls.py looks like this: path('e/country/<slug:slug>', ExpertCountryView.as_view(), name="expert_country") Now I am confused with my views.py how can I create my view (ExpertCountryView) to shows me experts with this industry. example: www.mysite.com/p/country/trade trade is my industry. I hope all is understandable. -
How to display specific output for specific username in django?
I have made a simple django app. In my models.py I have defined a table- class events(models.Model): id_campaign = models.CharField(default='newevent',max_length=100) status = models.CharField(default='100',max_length=100) name = models.CharField(default='100',max_length=100) This is my views.py - from django.shortcuts import render # Create your views here. from django.views.generic import TemplateView from django.shortcuts import render from website.models import * from website.models import events from django.views.generic import ListView class HomePageView(TemplateView): template_name = 'base.html' class AboutPageView(TemplateView): template_name = 'about.html' class ContactPageView(TemplateView): template_name = 'contact.html' class Success(TemplateView): template_name = 'success.html' def get_context_data(self, **kwargs): context = super(Success, self).get_context_data(**kwargs) query_results = events.objects.all() context.update({'query_results': query_results}) return context And this is the success.html - {% if user.is_authenticated %} <header> <a href=" {% url 'logout'%}">Logout</a> </header> {% block content %} <h2>you are logged in successfully. this is your personal space.</h2> <table> <tr> <th>id_campaign</th> <th>status</th> <th>name</th> </tr> {% for item in query_results %} <tr> <td>{{ item.id_campaign }}</td> <td>{{ item.status }}</td> <td>{{ item.name }}</td> </tr> {% endfor %} </table> {% endblock %} {% else %} <h2>you are not logged in.</h2> {%endif %} I need to check the username in success.html and based on the user I need to show results, how do I do that? if request.user.is_authenticated(): username = request.user.username if username is 'xyz' then I want … -
How do I get a param inside an URL in django admin?
I use django admin and want to access the object id in an URL like this: http://localhost:8000/polls/platform/837/change class PlatformAdmin(admin.ModelAdmin): def get_queryset(self, request): print(request.??) So what should be returned is the 837 -
How to validate Stripe in django-form-tools?
I've a 5 form wizard, with the last step taking credit card details using Stripe. I need to validate the Stripe details and return the user to the form should they generate payment card error. I am doing something like this def done(self, form_list, form_dict, **kwargs): stripe.api_key = settings.STRIPE_SECRET_KEY .... try: card_token = Card.create_token ( number=self.request.POST['checkout-cardNumber'], exp_month = int(self.request.POST['checkout-expiryDate'].split('/')[0]), exp_year = int(self.request.POST['checkout-expiryDate'].split('/')[1]), cvc = self.request.POST['checkout-cvv'], ) except Exception as e: return HttpResponseRedirect(self.request.META.get('HTTP_REFERER')) ... I know this isn't returning an error message but the bigger problem is because I'm in the done method form-tools has cleared the form wizard and it returns me to a blank form at the start of the process. With that in mind I started adding to the clean method of the form. stripe.api_key = settings.STRIPE_SECRET_KEY try: card_token = Card.create_token ( number=cleaned_data['cardNumber'], exp_month = int(cleaned_data['expiryDate'].split('/')[0]), exp_year = int(cleaned_data['expiryDate'].split('/')[1]), cvc = cleaned_data['cvv'], ) except Exception as e: if "Your card number is incorrect." in str(e): self.add_error('cardNumber', "Your card number is incorrect.") else: self.add_error('cardNumber', e) This works great for this example but the next step is to process the card using something like: try: djstripe_customer = Customer.objects.get(subscriber=self.request.user) customer = stripe.Customer.retrieve(djstripe_customer.id) customer.sources.create(source=card_token) except: #deal with exception pass The problem here … -
for i, middleware in enumerate(settings.MIDDLEWARE): TypeError: 'NoneType' object is not iterable
I got this error when i try to run python manage.py runserver or any other python manage.py * commands in command line. but when i tried python manage.py shell it connected without error and gets data from database. error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fa03b7386a8> Traceback (most recent call last): File "/home/tornike/apps/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/tornike/apps/env/lib/python3.6/site-packages/debug_toolbar/apps.py", line 25, in check_middleware for i, middleware in enumerate(settings.MIDDLEWARE): TypeError: 'NoneType' object is not iterable MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware' ) -
Django ORM get instance with unique ManyToMany [duplicate]
This question already has an answer here: Django queryset get exact manytomany lookup [duplicate] 1 answer Here is my issue: I want to grab the model instance that has a unique set of ManyToMany instances. For example, I have 3 models (one is a joint table): class Itinerary(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class FlightLeg(models.Model): flight = models.ForeignKey('flights.Flight', on_delete=models.CASCADE, related_name='flight_legs') itinerary = models.ForeignKey('itineraries.Itinerary', on_delete=models.CASCADE, related_name='flight_legs') class Flight(models.Model): itineraries = models.ManyToManyField( 'itineraries.Itinerary', through='itineraries.FlightLeg', related_name='flights' ) I'd like to query the Itinerary instance that has a particular list of flights. For example, let's say I have an Itinerary that has 3 flights with id 1,2,3 respectively. Let's say I have another Itinerary with ids 2,3. In both these cases, I'd like to query the itinerary that has a unique set of flights. So if I query an itinerary with flight id 1 and 2 it should not return the one with flight ids 1,2,3. Right now I've tried this but it obviously doesn't work: flights = [<Flight: B6 987>, <Flight: AM 401>, <Flight: AM 19>] query = reduce(and_, (Q(flight_legs__flight=flight) for flight in flights)) itinerary = Itinerary.objects.filter(query) I only want to return the Itinerary that has these 3 flights and nothing else. … -
How to modify a many-to-many collection using django rest framework
I am trying to create an endpoint where, having a User entity, I can add / remove existing Group entities to user.groups many-to-many field. But when I try to do it, django-rest-framework tries to create new group objects instead of finding existing ones. I have defined two serializers where UserSerializer has a nested GroupSerializer: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ['id', 'name'] class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'groups'] groups = GroupSerializer(many=True) def update(self, instance, validated_data): data = validated_data.copy() groups = data.pop('groups', []) for key, val in data.items(): setattr(instance, key, val) instance.groups.clear() for group in groups: instance.groups.add(group) return instance def create(self, validated_data): data = validated_data.copy() groups = data.pop('groups', []) instance = self.Meta.model.objects.create(**data) for group in groups: instance.groups.add(group) return instance When I send a JSON: { "id": 6, "username": "user5@example.com", "email": "user5@example.com", "groups": [ { "id": 1, "name": "AAA" } ] } I expect serializer to find the Group with given id and add it to User. But instead, it tries to create a new user group and fails with duplicate key error: { "groups": [ { "name": [ "group with this name already exists." ] } ] } I searched over … -
reverse for app_list error while customizing my admin
while customizing admin page in django facing this error " Reverse for 'app_list' not found. 'app_list' is not a valid view function or pattern name. " but i dont created a view named app_list i have created a directory named admin and created base_site.html file in it admin/urls.py from django.urls import path from .views import InvoiceList, MerchantUserList, SupportStatusUpdate from django.contrib import admin admin.autodiscover() urlpatterns=[ path( 'home/', admin.site.admin_view(InvoiceList.as_view()), name='home' ), path( 'user/list/', admin.site.admin_view(MerchantUserList.as_view()), name='user_list' ), path( 'support/update/<int:pk>/', admin.site.admin_view(SupportStatusUpdate.as_view()), name='support_update' ) ]