Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax Post method not detected in django
I'm discovering Ajax with Django and cannot to make them work. Before I continue, the project directory looks like this: mySite | |-> myApp |-> views.py |-> urls.py | ... // other py-files and directories |-> mySite |-> urls.py | ... // other py-files When I run the site and trigger the event for sending an Ajax request, I get a status 200 code but the function in views.py doesn't get executed so I assume that my urls.py is not properly configured. The Javascript implementing the Ajax post: function sendReq(){ console.log('AJX'); $.ajax({ type: 'POST', url: 'ajax_test', data:{ name: 'AjaxReq', val: '...', csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, sucess:function(){ console.log('SUCCES!'); } }); console.log('AJX done'); } The urls.py of myApp: from django.conf.urls import url from . import views urlpatterns = [ url(r'^', views.index, name='index'), url(r'^ajax_test', views.ajax_test, name='ajax_test'), ] The urls.py of mySite: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^',include('myApp.urls')), ] And finally the views.py of myApp: from django.shortcuts import render from django.http import JsonResponse def index(request): return render(request, 'myApp/index.html') def ajax_test(request): if request.method == 'POST': name = request.POST.get['name', None] val = request.POST.get['val', None] print(name + ': ' + val) I found different solution but seemed outdated. Can someone … -
Django admin panel app model list_display not showing
Here is my code from django.contrib import admin from farmer.models import * class listAllFarmer(admin.ModelAdmin): list_display = ('username', 'code') admin.site.register(allFarmers, listAllFarmer) if I write this only it works from django.contrib import admin from farmer.models import * admin.site.register(allFarmers) -
Django Inner Join tables with queryset
I'm trying to INNER join 2 tables. Comments and Auth. So i store userid in comment table and i need to pair it with auth. I did with .raw() but i don't want to do with raw, i have tried also other like get_objects_or_404 but that does not work either because of multiple querys. Here is my query works as excepted. "SELECT * FROM index_comment INNER JOIN auth_user WHERE index_comment.userid=auth_user.id" So i need to pair userid from comment table to auth id, and then get the username. -
django.core.exceptions.FieldError: Unknown field(s)
I've seen a lot of issues similar to mine, but none had exactly the same problem. I have my code running on another machine and it's working perfectly, it's exactly the same code since I'm using github for version control, but when I run on my machine I started to get this error, I use postgres, I already tried give drop in the database and create another but continue with this error. The error started after I imported the database from the machine that is running fine. When I tried to go back to the local database, I started to have an error, I already tried to reinstall all the packages (those installed via pip) and nothing. -
does django saves Charfield as strings?
so basic and confused about this question. i tried to see type of some objects in django and equals together . see example below : print(type(request.data['token'])) >>> <class 'str'> and : obj = UserProfile.objects.get(pk=1) print(type(obj.first_token)) >>><class 'app.models.first_token'> obj.first_token is a charfield. so how can i know that first_token stored as string? if request.data['token'] == obj.first_token: are this two objects equals if have a same value in them? -
Django how to build an invoice that gives the user the ability to add multiple items?
I am trying to build a e-shop using django 2.0, but I have a 'logic' question not a syntax one, how to build an invoice that can accept many Items? In other words I have a model for the invoice item that is connected To a product model but I do not know how to build an invoice view that That gives the user the ability to add multiple items to this invoice How to do so knowing that I use CBV for the views? Thanks in advance -
LoginView with Success
I am currently working with my Django authentification app. My goal is once the user logged in successful I want to redirect it to the index page where my code shows a customised message: messages.success(request, 'Login Successful', extra_tags='alert alert-dark') My problem is I didn't manage to 'access' LoginView in my views.py. I read about SuccessMessageMixin, but this LoginView won't work (Template Not Found): class LoginView(auth_views.LoginView): template_name = "accounts/login.html" Do you have any idea how to solve this? Only as long I include template_name in my urls.py it works, but I can't add the success message mixin there. urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='accounts/login.htm'), name='login'), ] -
Django - Increase a model field based on another model
I have a model called Product and a model called Stock. The model Product has a field called 'stock_current' that should show the current stock of an product and in model Stock has a field called 'quantity'. I'm looking for a way to when register one entry in model Stock, the field 'stock current' of Product's model get the current number and increase with the field 'quantity' of Stock model. I'm totally lost since i am a beginner with django. #model class Product(models.Model): name = models.CharField(max_length=200) code = models.CharField(max_length=200) cost = models.FloatField(blank=True, null=True) price = models.FloatField(blank=True, null=True) stock_min = models.IntegerField(blank=True, null=True) stock_current = models.IntegerField(blank=True, null=True) stock_control = models.BooleanField(default=True) class Stock (models.Model): product = models.ForeignKey(Product, blank=False, null=False) quantity = models.IntegerField(blank=False, null=False) #views def stock_add(request, stock_id=None): if stock_id: v_stock = Stock.objects.get(pk=stock_id) else: v_stock = None if request.method == 'POST': form_stock = StockaddForm(request.POST or None, instance=v_stock) if form_stock.is_valid(): resp = form_stock.save() if resp: messages.success(request, "Product has been registred !") return redirect('/') else: form_stock = StockaddForm(instance=v_stock) context_dict = {} context_dict['form_stock'] = form_stock return render(request, 'admin_panel/register/stock_add.html', context_dict) Until now i just know the way how to register a stock. The question is how to add the value of 'quantity' field to 'stock_current' field of a … -
Django Internationalization Broken URL
i followed all of the steps for the internationalization. I created the messages and compiled them for en and ro. When i go to my localhost /en/ i can see all of the items from navbar. The same when i go to my /ro/ site. But them i click from /ro/ to /ro/aboutus, instead of going to the romanian page of about us {"Despre noi"} i am redirected to en/about us. Do you know why this happens? Thank you! -
Modeling multiple many to many relationships
My goal is to create a voting API for users to make a Choice selection from a list of choices. Choice can be anything like cars, food, travel location, etc. Each user will select their choice then the votes will be tallied up and displayed. For instance, to create a vote, I would access the endpoint /votes. In the json data I would add the users I want in the vote group as well as indicate my own vote, sending something like this: Post: {creator: "self" vote_attr: 5 particiants: [{ user : "self", choice: "35"}, { user : "2", choice: ""}, { user : "3", choice: ""}, ] } Response: { vote_id: 23 vote_attr: 5 creator: "self" participants: [{ user : "self", choice: "35"}, { user : "2", choice: ""}, { user : "3", choice: ""}, ] } I'm having trouble figuring out how to represent this relation in DRF. I've read up on through models and nested relationships but still don't fully understand either as well as which will be needed for my what I'm trying to do. models.py class User(models.Model): name = models.CharField(max_length = 50) email = models.CharField(max_length = 50) class Choice(models.Model): name = models.CharField(max_length = 50) description … -
How to enable daily new filename of logging in Python Django's Settings?
I want to log the calling of restful api on each day into yyyy-mm-dd.log. In settings.py I write: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' }, }, 'handlers': { 'infofile': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'C://mydoc/logs/'+str(datetime.date.today())+'.log', 'formatter':'standard', }, }, 'loggers': { 'django': { 'handlers': ['infofile'], 'propagate': True, }, }, If the server started e.g. on 01.01.2018, the "2018-01-01.log" will be created and all logs will be written into the file, even the callings is on 15.01, because the settings.py is run only one time on 01.01 at the server's starting. How can Django create everyday a new log file and use the file? -
MetaTrader 4 MT4 api
So, im developing backed in Python Django. Client is asking to implement synchronization with MT4 system. I tried to find solution, but all is dead end. Everything they are saying is here are the dlls use them in you .NET project, etc. I want to ask you if somebody has done this in some other language using something other than .NET (eg python, php, nodejs, java) and if that works in Linux environment, since our server is Ubuntu? -
If-None-Match header not accepted request header
I'm trying to understand how Etag works in Django. I added middleware in settings ('django.middleware.http.ConditionalGetMiddleware') and this seems to work as it generates the Etag: HTTP/1.0 200 OK Date: Mon, 15 Jan 2018 16:58:30 GMT Server: WSGIServer/0.2 CPython/3.6.0 Content-Type: application/json Vary: Accept Allow: GET, HEAD, OPTIONS X-Frame-Options: SAMEORIGIN Content-Length: 1210 ETag: "060e28ac5f08d82ba0cd876a8af64e6d" Access-Control-Allow-Origin: * However, when I put If-None-Match: '*' in the request header, I get the following error: Request header field If-None-Match is not allowed by Access-Control-Allow-Headers in preflight response. And I notice the request method sent back in the response is OPTIONS and the rest of the headers look like this: HTTP/1.0 200 OK Date: Mon, 15 Jan 2018 17:00:26 GMT Server: WSGIServer/0.2 CPython/3.6.0 Content-Type: text/html; charset=utf-8 Access-Control-Allow-Origin: * Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Max-Age: 86400 So the question is how do I get If-None-Match to be an allowed header? I'm not sure if this is a server or client issue. I'm using Django/DRF/Vue for my stack and Axios for making http requests. -
Combine DjangoObjectType and ObjectType
I have a simple django model with a calculated property field clicks. The model looks like this: class Link(models.Model): url = models.URLField() @property def clicks(self): """ Property does some calculations and returns a list of dictionaries: """ # removed calculation for simplicity return [{'dt': 1, 'clicks': 100}, {'dt': 2, 'clicks': 201}] I want to make this model accesible in my graphql endpoint. So I created the following Types and Query: class Stats(graphene.ObjectType): clicks = graphene.String() dt = graphene.String() class LinkType(DjangoObjectType): clicks = graphene.List(Stats, source='clicks') class Meta: model = Link class Query(object): link = graphene.Field(LinkType, id=graphene.Int()) def resolve_link(self, info, **kwargs): id = kwargs.get('id') url = kwargs.get('url') if id is not None: return Link.objects.get(pk=id) return None Now I should be able to use the following query in my graphql explorer: { link(id: 3) { id, url, clicks{ clicks, dt } } } My expected result would be like this: { id: 3, url: "www.google.de", clicks: [ dt: 1, clicks: 100}, dt: 2, clicks: 201} ] } But the nested values of clicks and dt are null: { id: 3, url: "www.google.de", clicks: [ dt: null, clicks: null}, dt: null, clicks: null} ] } So what am I doing wrong here? How can … -
Django: Custom manager method VS model method to override create?
I'm not sure to understand the actual purpose of using a create_object() method in a custom manager, rather than directly in the model, when I need to override the default Class.objects.create() method. The only difference I see is how I would call it: Class.create_object() if the create_object() method is in the model Class.objects.create_object() if the create_object is a custom manager method. However, I suppose the latter is the right thing to do, based on examples I can see from Django (with create_user for example). I just would like to understand why. Thanks! -
Django Crispy forms with ModelForm, none type has no attribute fields, wrap_together
Im new to crispy forms and am trying to add some layout to the forms, by putting them in three groups, then id like to put them in some panels (im using boostrap3) this is my forms.py class EditSiteForm(forms.ModelForm): class Meta: model = SiteData fields = ['location', 'site_type', 'bgp_as', 'opening_date','last_hw_refresh_date','is_live', 'tel','address','town','postcode', 'regional_manager','regional_manager_tel','assistant_manager','assistant_manager_tel' ,'duty_manager','duty_manager_tel'] helper = FormHelper() helper.form_method = 'POST' helper.add_input(Submit('Save', 'Save', css_class='btn-primary')) helper[0:5].wrap_together(Field, 'Details') helper[6:9].wrap_together(Field, 'Address') helper[10:15].wrap_together(Field, 'Showroom Contacts') when I load the page I get Exception Value: 'NoneType' object has no attribute 'fields' Exception Location: /usr/local/lib/python3.6/site-packages/crispy_forms/layout_slice.py in wrap_together, line 107 is modelform not support in crispy? do I need to issue each field manually first? Thanks -
Django FormTools Dynamic Form Not Saving Data
I am using Django Formtools for the forms: https://django-formtools.readthedocs.io/en/latest/ Currently Happening: Dynamically generated form and form fields are being displayed. Enter some data into the said fields, but self.get_all_cleaned_data() returns nothing. Form returns to page 0 instead of submitting the form and using done() What I want to happen: - Data in fields to be retained and displayed when going back, or to the confirmation page - Form to actually submit and use done() to process and save The following the my forms.py class OrderForm(forms.Form): class Meta: localized_fields = ('__all__',) def __init__(self, *args, **kwargs): self.fields = kwargs.pop('fields') fields = self.fields super(OrderForm, self).__init__(*args, **kwargs) if not isinstance(fields, str): for i in fields.fields.all(): widget = forms.TextInput() _type = forms.CharField if i.field_type == Field.TEXTAREA_FIELD: widget = forms.Textarea ... self.fields[i.name] = _type(**fields) This is supposed to get Database created forms and field data and generate fields accordingly. For example: Form A has fields: Name (Regular Text Field) Address (Textarea) The above code will then generate fields for those. The next block of code is from my views.py file FORM_TEMPLATES = { "0": 'order/details.html', "1": 'order/details.html', "2": 'order/details.html', "3": 'order/details.html', "4": 'order/details.html', "confirm": 'order/confirm.html', } class Order(SessionWizardView): form_list = [OrderForm] def get_current_step_form(self, company, *args, **kwargs): … -
DRF: Validate nested serializer data when creating, but not when updating
When using writable nested serializers in DRF there is the known problem with validating eventual unique fields and preventing the updating of the parent serializer. This issues has been asked many times in questions like these: Unique validation on nested serializer on Django Rest Framework Django rest framework not creating object with FK to a model with unique=True field For simplicity let's take the example from the first question: class GenreSerializer(serializers.ModelSerializer): class Meta: fields = ('name',) #This field is unique model = Genre extra_kwargs = { 'name': {'validators': []}, } class BookSerializer(serializers.ModelSerializer): genre = GenreSerializer() class Meta: model = Book fields = ('name', 'genre') def create(self, validated_data): # implement creating def update(self, instance, validated_data): # implement updating Now the problem is that the uniqueness validation is dropped out also for creating. This could be intercepted in the view, for example: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer = BookSerializer def perform_create(self): # implement logic and raise ValidationError However this doesn't feel really right because we're validating the uniqueness of Genre in BookViewSet. The other option is to implement the validation in the create() method of BookSerializer as explained in the second question (see list above). What I really miss in both … -
2018 Django Internationalization for 3 languages site
i have tried to use different sources from StackOverflow in order to make my site to accept by default my language and not EN. During the research over the Internet I couldn't find a real solution that can help me to use my own language. I've tried until now, which is my source code: LANGUAGE_CODE = 'ro' from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('ro', _('Romanian')), ('en', _('English')),) DEFAULT_LANGUAGE = 1 Middleware like this post:\https://gist.github.com/vstoykov/1366794\ or Django default language but they don't really work in django 2.0. Can someone please help me with my issue? Thank you! -
Modify models field via view doesn't work
In my Django application, I want to subtract 1 "free_places" field in the "Event" model using the "EventDetailView" view where the form is located. Each time the form is OK (when the user subscribes to the event), the "free_places" field should decrease by 1. I do not know why my code does not work. My view: class EventDetailView(DetailView, ModelFormMixin): model = models.Event form_class = forms.RegisterForm context_object_name = 'event' def get_success_url(self): return reverse('events:list') def get_initial(self): return {'event': self.kwargs['pk']} def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): self.object = self.get_object() self.object.free_places - 1 self.object.save() return self.form_valid(form) else: return self.form_invalid(form) Models: class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() text = models.TextField() image = FilerImageField(null=True, blank=True) flag = models.ForeignKey(Flag) free_places = models.IntegerField() class Meta: ordering = ['-date'] def __str__(self): return self.title @property def slug(self): return slugify(self.title) def get_absolute_url(self): return reverse('events:detail', args=[self.slug, self.id]) def get_model_id(self): return self.id class Register(models.Model): event = models.ForeignKey(Event) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) company = models.CharField(max_length=30, blank=True) street = models.CharField(max_length=50, blank=True) post_code = models.CharField(max_length=30, blank=True) city = models.CharField(max_length=30, blank=True) email = models.EmailField() phone_number = models.IntegerField() def __str__(self): return self.first_name def get_event_name(self): return self.event -
Testing circular reference models in Django
I have two tables/models with a circular reference one to another. When I run my tests, Django tries to flush the database (delete all tables, one by one) and then recreate it again for the next test. The problem is that when Django gets to one of those two tables, it crashes, saying that "can't truncate a table referenced in a foreign key constraint". This behaviour is actually quite logical, but unfortunately for me, not very helpful in my case. Is there any way I can make Django not try to commit after each DELETE, or maybe just delete all tables at once? -
How to dispay django auth user list in django suit dashboaard
I have used django suit dashboard. And customize admin side. Its working but default django auth user list not display. So, How to display auth user list with django suit dashboard. -
Django Restframework _ update user model with special custom token?
in DRF i have a some custom action that will do something to user model.user instances are all in state of is_active = False.Im trying to make something that turns the user to is_active = True. i made some a token model that has OneToOne to my user model.the function im trying to make is : if token that user put in the form equals to user.token then set user.is_active = True.im confused how to do that. I made my own serializer class : class ActivateUserSerializer(serializers.ModelSerializer): phonenumber = serializers.CharField() token = serializers.CharField() class Meta: model = UserProfile fields = ['phonenumber','token'] def get_token(self, obj): request = self.context.get('request') x = request.data['phonenumber'] obj = UserProfile.objects.get(phonenumber=x) if request.data['token'] == obj.first_token: obj.is_active = True obj.save() i know this is not .create() .or update() function.so this is how I reach so far.I dont know what view i should use for this functionality. -
Does heroku app have to share the same name as django project?
I'm trying to deploy an app that I started with django-admin startproject workout. Months later, it was time to deploy, workout was not an available name for heroku apps. Thus, I decided on shworkout. Now, I'm having problems with the deployment. Take a look at this traceback: 2018-01-15T13:50:49.922410+00:00 heroku[web.1]: Starting process with command `gunicorn shworkout.wsgi --log-file -` 2018-01-15T13:50:52.274803+00:00 app[web.1]: [2018-01-15 13:50:52 +0000] [4] [INFO] Starting gunicorn 19.7.1 2018-01-15T13:50:52.275393+00:00 app[web.1]: [2018-01-15 13:50:52 +0000] [4] [INFO] Listening at: http://0.0.0.0:57296 (4) 2018-01-15T13:50:52.275484+00:00 app[web.1]: [2018-01-15 13:50:52 +0000] [4] [INFO] Using worker: sync 2018-01-15T13:50:52.278566+00:00 app[web.1]: [2018-01-15 13:50:52 +0000] [8] [INFO] Booting worker with pid: 8 2018-01-15T13:50:52.283407+00:00 app[web.1]: [2018-01-15 13:50:52 +0000] [8] [ERROR] Exception in worker process 2018-01-15T13:50:52.283421+00:00 app[web.1]: Traceback (most recent call last): 2018-01-15T13:50:52.283428+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 2018-01-15T13:50:52.283430+00:00 app[web.1]: worker.init_process() 2018-01-15T13:50:52.283431+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process 2018-01-15T13:50:52.283433+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 2018-01-15T13:50:52.283432+00:00 app[web.1]: self.load_wsgi() 2018-01-15T13:50:52.283434+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-01-15T13:50:52.283443+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2018-01-15T13:50:52.283441+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2018-01-15T13:50:52.283442+00:00 app[web.1]: self.callable = self.load() 2018-01-15T13:50:52.283446+00:00 app[web.1]: return util.import_app(self.app_uri) 2018-01-15T13:50:52.283448+00:00 app[web.1]: __import__(module) 2018-01-15T13:50:52.283444+00:00 app[web.1]: return self.load_wsgiapp() 2018-01-15T13:50:52.283445+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2018-01-15T13:50:52.283449+00:00 app[web.1]: ModuleNotFoundError: No module named 'shworkout' … -
Django - Liste index in template
i have a probleme with my template. I know how to use list.index to get a value from a list, but now my index value is container.id (=1) so i have supidly try list.container.id and is not working like list.1