Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest serializing model with foreign key self
I made a custom User model and trying to implement fields, that shows user that update another user. But can't understand, how to write serializer properly to serialize model.self. How can I do that? I tried write it like you can see below, but got errors like Incorrect type. Expected pk value, received MainUser. or just get created_by field with null My model: class MainUser(AbstractBaseUser): email = models.EmailField(unique=True) phone = models.IntegerField(unique=True) password = models.CharField(max_length=15) first_name = models.CharField(max_length=20, null=True, blank=True) last_name = models.CharField(max_length=20, null=True, blank=True) token = models.CharField(default=secrets.token_urlsafe(250), max_length=334, unique=True) group = models.ForeignKey(Group, blank=True, null=True) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) deleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey('self', blank=True, null=True, related_name='created_user') updated_at = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey('self', blank=True, null=True, related_name='updated_user') deleted_at = models.DateTimeField(blank=True, null=True) deleted_by = models.ForeignKey('self', blank=True, null=True, related_name='deleted_user') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = BaseUserManager() def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True class Meta: ordering = ('email',) My view: class UserManagerAdmin(APIView): def post(self, request, format=None): current_user = checkUserToken(request.query_params.get('token')) if current_user is None: return request.data['admin_user']['created_by'] = current_user serializer = UserSerializer(data=request.data['admin_user']) if serializer.is_valid(): serializer.validated_data['password'] = make_password(serializer.validated_data['password']) # serializer.save() return Response(serializer.data, status=201) return … -
Add Dynamic custom variable in logging Formatter Django Python
Let the Following be the logging formatter in settings.py` LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %thread)d %(message)s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, }, 'myproject.custom': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, } } } Now Say I have three files namely A.py, B.py & C.py In A.py I have a decorator def myDecorator(): #Code to generate unique Id for each request in Django APP uniqueId = #something In B.py & C.py i have many functions to handle various requests import A.py import myDecorator import logging @myDecorator def func1(): #Some Code logger.debug("Logger message") @myDecorator def func2(): #Some Code logger.info("Logger message") @myDecorator def func3(): #Some Code logger.debug("Logger message") def func4(): #May be Some functions without logger too !!!! logger.debug("Logger message") Now I want to log the generated unique Id along with the logger message without being passed explicitly every time in the logger & I also want to make it generic ! Is there by any way I can pass these unique ID's to loggers without passing it explicitly. 'formatters': { 'verbose': { 'format': '%(levelname)s … -
Parsing CSV data to D3 using Django
I'm developing a Django app for data visualization and trying to upload csv file with following code: d3.csv("data.csv", function (myData){ console.log(myData[0]) }); I have tried to copy file in the same folder where my html file is and also by copying it into the root folder but I get following error in my browser console: d3.min.js:7 GET http://localhost:8000/home/data.csv 404 (Not Found) Can anyone please help? Thanks -
How do I point my reserved domain to a Django EC2 instance?
Ok so I'm hosting a Django EC2 instance right now using ngrok http 8000 and leaving it running. It's doing fine but a lot of browsers are blocking the traffic to my site. I need to make my reserved domain (I have some on Amazon and some on 1 and 1) to my 123.4.5.67:8000 public IPv4 IP or just my public IPv4 DNS on my EC2. What I need in a nutshell is example.com to redirect to 123.4.5.67:8000 while still saying example.com in the url. So far I have heard of Apache, WSGI, and nginx. None of them have worked for me, but maybe I haven't gotten the right direction. Please help! -
django :(name '_' is not defined),(validation error not working),( I can see alphabets while creating password)
I am using python version 3.5 and django version 1.11 here is my all code first problem is "name '_' is not defined" after submitting the form. second problem is "raise.validationerror is not working" (forms.py). third problem id " I can see alphabets while creating passwords in password field. what field should I use for phone number. forms.py class Employee_registration(ModelForm): class Meta: model = Employee fields = '__all__' def clean(self): password=self.cleaned_data['password'] repeat_password =self.cleaned_data['repeat_password'] if password != repeat_password: raise forms.ValidationError(_('password did not match')) views.py def registration_of_new_employee(request): if request.method == 'POST': form = Employee_registration(request.POST) if form.is_valid(): form.save() return render(request, 'website/registration_of_new_employee.html',{'form':Employee_registration}) models.py class Employee(models.Model): name = models.CharField(max_length=50,null=True) username = models.CharField(max_length=100,null=True) password = models.CharField(max_length=128) repeat_password = models.CharField(max_length=128) email = models.EmailField(max_length=70,null=True) phone_number = models.IntegerField(default=0) permanent_address = models.CharField(max_length=100,null=True) alternative_address = models.CharField(max_length=100,null=True) salary = models.IntegerField(default=0) join_date = models.DateField(null=True) paid_salary_date = models.DateField(null=True) designation = models.CharField(max_length=50,null=True) def __str__(self): return self.name registration of new employee.html {% extends 'website/base.html' %} {% block main_content %} <div class="registion_container" align = "center"> <h2>Registration of new employee</h2> <form method="post" action="{% url 'website:registration_of_new_employee' %}"> {% csrf_token %} {% for field in form %} <ul> <li>{{ field.errors }} {{ field.label_tag }} {{ field }}</li> </ul> {% endfor %} <input type="checkbox" checked="checked"> Remember me <p>By creating an account … -
Django Queryset - separate objects by attribute
I have objects in the database, for example: John, Student Marry, Student Alice, Teacher Peter, Teacher Louis, Student and I want to create queryset what will separate this objects by one attribute: {'Student': [ <John>, <Marry>, <Louis> ], 'Teacher': <Alice>, <Peter> ]} Is it event possible to get this result by one queryset? -
When you have two models connected by a foreignkey in django do you need to do a join?
The Django docs are not plainly stating this and its getting annoying. Observe the following models: # models class Venue(models.Model): name = models.CharField(max_length=150, blank=False) description = models.CharField(max_length=1000) image = models.ImageField(upload_to=imgUnique('venueMedia/venueImages')) streetAddress= models.CharField(max_length=100) city = models.CharField(max_length=100, blank=False) state = models.CharField(max_length=100, blank=False) class Room(models.Model): name = models.CharField(max_length=150, blank=False) venue = models.ForeignKey(Venue, related_name='rooms', on_delete=models.CASCADE) description = models.CharField(max_length=1000) standingCapacity = models.IntegerField seatedCapacity = models.IntegerField image = models.ImageField(upload_to=imgUnique('venueMedia/venueImages')) I have a foreign key relationship into Venue in the Room model in the rooms venue property. Do I need to join those tables? Or will a Venue.objects.all() do that for me automatically? If not I have the raw sql as follows will this work: venueList = Venue.objects.raw('''SELECT * FROM venue_Venue INNER JOIN venue_Room ON venue_Venue_id=venue_Room_id''') if not that then I understand there is a select_related() method and my understanding is that I would do the following: Venue.objects.all().select_related('Room') Can we get this clear? As you can see I have done alot of research but still confused -
Is Django recommended to use with mod_wsgi?
For using Django, mod_wsgi apache module is an alternative to mod_python and mod_fcgid solutions, in Apache HTTP server. Question: In real time projects, Is Django web app framework recommended to be used with mod_wsgi apache module? -
Django with daemon
I have a rather complicated data model that may be large and is mostly saved physically. As such a, C daemon is running to handle it. This needs to be glued to a Django web-server. There are two type of requests I need: Fast - giving a quick synchronous call in order to serve a response to the user. Slow - Needs to provide a 'Fast' response, and continue working on more complicated calculations offline. I started implementing a socket interface between the daemon and the interface before reasoning it's probably already done and better. I'm open to anything, including extending the C code to Python. I was looking at Celery but it seems to need another handler as well, and I'm trying to be lightweight as possible - though if that's best I'll try harder to use it. I just need an easy RPC-like system between the server and the daemon. -
django in production generates cahe page everytime opening url
I have a site on django. It generate cahe page each time for I open it. I can't find out the reason. Here is wsgi application + ngix. This is not personal server, I asked support ofcause, but I want to know what the reason is! I thought about html5min, but without cashe doesn't load< but generates new pages in it. Production is python 2.7 + Django last + Wagtail last In test mode when djangos server is alone, the cache works correct. On test is is python 3 + Django last + Wagtail last Annother question is: does wsgi application every time runs django? Or it needs to run it manualy? If so, how to look if it runs on hosting? Plase help me! -
Django views.py request and query
I have a contact page for my website. The contact form is working but I want to add a background image to this page (which is saved in the database).But how can I combine my email(request) and a query to get the image ? views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import ContactForm def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('./success') return render(request, "contact/email.html", {'form': form}) def success(request): return HttpResponse('Success! Thank you for your message.') models.py from django.db import models class Background(models.Model): name = models.CharField(max_length=200, null=False) image = models.ImageField(upload_to='./background/', default=None) def __str__(self): return self.name urls.py from django.conf.urls import url from . import views app_name = 'contact' urlpatterns = [ url(r'^$', views.email, name='email'), url(r'^success/$', views.success, name='success'), ] -
Changing the settings file when using django and gunicorn together
I've deployed my Django project using this tutorial and it works fine. Now I want to split the settings file and have multiple settings in development and production environments. I created a settings directory and added these files into the directory: my_project/ manage.py my_project/ __init__.py urls.py wsgi.py settings/ __init__.py base.py dev.py prod.py The base.py is same as former settings.py (that was working fine). I imported base.py and added DEBAG=False and ALLOWED_HOSTS to prod.py. How can I tell the gunicorn to run my application with prod settings? The gunicorn.service file, based on the tutorial is like this: [Unit] Description=gunicorn daemon After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myproject ExecStart=/home/sammy/myproject/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/sammy/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target -
Why the Django server return the result data after serialized difference from $.ajax between POSTMAN
I'm using Django rest_framework to build API server, and I also using POSTMAN to test the logic. Every I OK until I using $.ajax to POST the data to Django server, after serializer server always return not is_valid(). After debug, I realized that some difference when POST data from $.ajax between POSTMAN. And i want to know what happen with it? I also show my code below: Django server: Serializer class: class MetadataPresentationObject(serializers.Serializer): id = serializers.CharField() order = serializers.IntegerField() class MetadataPresentationRequestSerializer(serializers.Serializer): order_metadata_presentation = MetadataPresentationObject(many=True) View class: class MetadataPresentationView(BaseAPIView): def post(self, request, *args, **kwargs): result = {'success': False} serializer = MetadataPresentationRequestSerializer(data=request.data) if serializer.is_valid(): list_update_order = [] for item in request.data['order_metadata_presentation']: list_update_order.append(MetadataPresentation( id=binascii.unhexlify(item['id']), order=item['order'] )) if len(list_update_order) > 0: bulk_update(list_update_order, update_fields=['order']) result['success'] = True return HttpResponse(json.dumps(result)) Client code (using $.ajax POST data): jQuery: $.ajax({ url: metadata_presentation_url, // the endpoint type: 'POST', // http method dataType: 'json', data: JSON.stringify(update_data), // handle a successful response success: function(response) { if (response != undefined && response != null && response.success) { ShowNotification('Sucess sort metadata presentation data'); } else { ShowNotification('Error sort metadata presentation data', true); } }, // handle a non-successful response error: function(xhr, errmsg, err) { ShowNotification('Error sort metadata presentation data', true); } }); Data … -
How can I JSON serialize a queryset on Django?
I'd like to return on my ajax response a queryset, this is the error I get when I try to serialize a queryset. TypeError: 'Font: FontName' is not JSON serializable I am using JSON response like so : ... return JsonResponse({ 'foo': Font.objects.filter(id=1).first(), }) I'd like to be able to get it back on response and display every fields in the query on my template. Is this even possible ? -
Websocket, python - an existing connection was forcibly closed by the remote host (django-channels)
So I getting the error as described in the title of this post. Here's the full traceback: In [1]: import websocket In [2]: ws = websocket.WebSocket() In [3]: ws.connect("ws://localhost:8000") --------------------------------------------------------------------------- error Traceback (most recent call last) <ipython-input-3-43b98f503495> in <module>() ----> 1 ws.connect("ws://localhost:8000") c:\Python27\lib\site-packages\websocket\_core.pyc in connect(self, url, **options) 212 213 try: --> 214 self.handshake_response = handshake(self.sock, *addrs, **options) 215 self.connected = True 216 except: c:\Python27\lib\site-packages\websocket\_handshake.pyc in handshake(sock, hostname, por t, resource, **options) 67 dump("request header", header_str) 68 ---> 69 status, resp = _get_resp_headers(sock) 70 success, subproto = _validate(resp, key, options.get("subprotocols")) 71 if not success: c:\Python27\lib\site-packages\websocket\_handshake.pyc in _get_resp_headers(sock, succe ss_status) 125 126 def _get_resp_headers(sock, success_status=101): --> 127 status, resp_headers = read_headers(sock) 128 if status != success_status: 129 raise WebSocketBadStatusException("Handshake status %d", status) c:\Python27\lib\site-packages\websocket\_http.pyc in read_headers(sock) 224 225 while True: --> 226 line = recv_line(sock) 227 line = line.decode('utf-8').strip() 228 if not line: c:\Python27\lib\site-packages\websocket\_socket.pyc in recv_line(sock) 99 line = [] 100 while True: --> 101 c = recv(sock, 1) 102 line.append(c) 103 if c == six.b("\n"): c:\Python27\lib\site-packages\websocket\_socket.pyc in recv(sock, bufsize) 78 79 try: ---> 80 bytes_ = sock.recv(bufsize) 81 except socket.timeout as e: 82 message = extract_err_message(e) error: [Errno 10054] An existing connection was forcibly closed by the remote host I have redis … -
internal server error while calling an api through retrofit 2.0
here the get request works perfectly fine but when i do this get request it doen't work but it through postman this is my api interface public interface AuthApi { @FormUrlEncoded @POST("students/") Call<Person> punch( @Field("name") String code, @Field("mobile") String mobile, @Field("time") String time, @Field("late") String late ); @GET("students/") Call<List<Person>> studentlist(); } this is my api call View.OnClickListener submitListener = new View.OnClickListener() { @Override public void onClick(View v) { if (name.getText().toString().equals("") || mobile.getText().toString().equals("") || mobile.getText().toString().length() != 10) { Toast.makeText(MainActivity.this, "please enter correct credentials", Toast.LENGTH_SHORT).show(); } else { date = new Date(); SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String time = localDateFormat.format(date); String late=""; if (date.getHours() == 10 && date.getMinutes() > 29 && date.getSeconds() > 0) { late=("late by: " + new Integer(date.getMinutes() - 30).toString() + "mins " + new Integer(date.getSeconds()) + "secs"); } else if (date.getHours() > 10) { late= ("late by: " + new Integer(date.getHours() - 10) + "hrs " + new Integer(date.getMinutes()).toString() + "mins " + new Integer(date.getSeconds()) + "secs"); } else { late="in time"; } mApi = new RetrofitHelper<AuthApi>().getApi(AuthApi.class); punchCall=mApi.punch(name.getText().toString(),mobile.getText().toString(),time,late); punchCall.enqueue(new Callback<Person>() { @Override public void onResponse(Call<Person> call, Response<Person> response) { Toast.makeText(MainActivity.this,"success",Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<Person> call, Throwable t) { Toast.makeText(MainActivity.this,"failed",Toast.LENGTH_SHORT).show(); } }); } } }; this … -
Append #label with links to scroll the page in django templates
I am populating a link using below line. <a role="button" href="{% url 'home:explore' %}">Contact Us</a> I need to append an html elements id with the link so that it will scroll to that location when the page opens. I tried adding the #label in the href as below. But, this adds an extra / before the #label. <a role="button" href="{% url 'home:explore' %}">Contact Us</a> Resulting link: home/explore/#contactus How to do this without adding the / after explore like this: /home/explore#contactus -
How to inject same context in many different Dango views?
I want to put info about one object in many views without repeating it in get_context_data in each view. As u understand i need a class with get_context_data inside, that i can mix with other views. Here in my example i want to see 'some_object' in context of UpdateAnotherObjectView: class BaseObjectInfoView(View): def get_context_data(self, **kwargs): context_data = super(BaseObjectInfoView, self).get_context_data(**kwargs) context_data['some_object'] = SomeObjects.objects.get(pk=1) return context_data class UpdateAnotherObjectView(BaseObjectInfo, UpdateView): template_name = 'create_object.html' form_class = AnotherObjectForm model = AnotherObjects def get_context_data(self, **kwargs): context_data = super(UpdateAnotherObjectView, self).get_context_data(**kwargs) context_data['all_another_objects'] = AnotherObjects.objects.all() return context_data it works, but get_context_data is not a part of parent 'View' class. May be i need more special class to inherit from in BaseObjectInfoView? or maybe better to construct context with another method ? -
Desktop app using Django and electron
I have built a django project and now I want to extend it's scope to desktop. How should I go about making a desktop app using Electron? -
Issues Implementing social-auth-app-django - missing required positional argument: 'uid'
for a little context, I recently completed the codeschool.com courses on Python and Django. I was following along with the "Build a Team Directory App with Django: Part 2" and everything was going swimmingly until I tried to implement the Google OAuth2 piece. I've since realized there is a new social-auth-app-django package and have read through the docs top to bottom but don't fully understand everything in there. So here's where I've managed to get. I am successfully getting redirected to the Google login screen and once I log in to Google, I then get the following error "TypeError: social_user() missing 1 required positional argument" Full traceback: Internal Server Error: /complete/google-oauth2/ Traceback (most recent call last): File "/Users/jeremiahflickinger/Desktop/td/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/jeremiahflickinger/Desktop/td/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/jeremiahflickinger/Desktop/td/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/jeremiahflickinger/Desktop/td/venv/lib/python3.6/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/jeremiahflickinger/Desktop/td/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Users/jeremiahflickinger/Desktop/td/venv/lib/python3.6/site-packages/social_django/utils.py", line 50, in wrapper return func(request, backend, *args, **kwargs) File "/Users/jeremiahflickinger/Desktop/td/venv/lib/python3.6/site-packages/social_django/views.py", line 32, in complete redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "/Users/jeremiahflickinger/Desktop/td/venv/lib/python3.6/site-packages/social_core/actions.py", line 41, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/Users/jeremiahflickinger/Desktop/td/venv/lib/python3.6/site-packages/social_core/backends/base.py", line … -
django invalid literal for int() with base 10: ','
I want to pass a url like this: /view/people/?roles=1,2 where 1,2 is formed from a javascript function. In my view I have this: roles=request.GET.get('roles',None) if roles: roles=list(roles) if type(roles) is list: filter_options['role__in']=roles and i get the above error. If I hard code roles as: filter_options['role__in']=[1,2,3] -
Serializing user groups as an array without keywords in Django Rest Framework
I am working on a Django project with the django_rest_framework. I am trying to create a serializer that returns a user with all the groups that he belongs to as a simple array. For example: { "username": "John Doe", "groups": "[Group1, Group2]" } My current configuration however returns the groups as objects and adds attribute names, so my previous example unfortunately returns as follows: { "username": "John Doe", "groups": "[{"name":"Group1"},{"name":"Group2"}]" } Are you able to get the achieve the result that I want with the django_rest_framework? Here are my serializers: serializers.py from django.contrib.auth.models import User, Group from rest_framework import serializers class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('name',) class UserSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) class Meta: model = User fields = ('username', 'groups') -
Djando debug by pyCharm on vagrant
I have a python project, running on vagrant machine. IDE is a pyCharm. Project syncs by vagrant synced_folder setting. Project running on apache wsgi by default. I am trying to debug my app, using django server configuration. But, i have only two options to run: run with coverage and profile.Run and debug buttons are disabled. What i do wrong ? And also, can i debug my up, running on apache wsgi ? -
How to test if a method is called using pytest
I want to write a unit test to check if a method is being called. Is there any way to do it. Or i am misunderstanding the way mock can be used here? As this way mocked_method is always called but without any args. @(pytest.parameterize) def test(jsonrpc_proxy): jsonrpc_proxy.method1_call() # Method 1 should not call method 2 with mock.patch('method2') as mocked_method: assert ((args),) not in mocked_track.call_args_list # do something jsonrpc_proxy.method1_call() # Method 1 should call method 2 with mock.patch('method2') as mocked_method: assert ((args),) in mocked_track.call_args_list PS: I have checked other questions related to it before posting, but i think i am misunderstanding the whole concept about how we use mock in such scenarios. Please enlighten me as i am new to this. -
formset validation in CBV
I have a Order form where I used formsets because I want the user to dynamically add more products and their quantity. The user enters the name of the order, and it is validated not to be empty. How do I validate the formset itself? to check that the product/quantity is not empty views.py class OrderCreateView(CreateView): model = Order template_name = "orderform.html" fields = ['name', ] def get_context_data(self, **kwargs): data = super(OrderCreateView, self).get_context_data(**kwargs) if self.request.POST: data['productmetas'] = InlineOrderFormSet(self.request.POST) return data def form_valid(self, form): context = self.get_context_data() productmetas = context['productmetas'] self.object = form.save(commit=False) self.object.save() if productmetas.is_valid(): productmetas.instance = self.object productmetas.save() return super(OrderCreateView, self).form_valid(form) models.py class ProductMeta(models.Model): order = models.ForeignKey(Order) product = models.ForeignKey(Product) quantity = models.FloatField() forms.py InlineOrderFormSet = inlineformset_factory(Order, ProductMeta, form=OrderAutoCompleteForm, extra=1)