Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-rest-framework and unique_together
I am writing and API, and due to the fact that it is based on the microservice architecture, and components run asynchronously, I cannot return an object id when the client creates an object. Some time later the client may wish to update the object, however, they don't know the id/pk. That said, there are several fields with the unique_together constraint on them. My initial idea was to override the create method and compare these fields on the objects that I receive with the ones in my DB, and, if I find any, update them, if I don't — create the object. However, that fails because the validation is run before the create method, and the validation fails for the "update" objects, because they break the unique_together constraint. I can't use those unique fields as a compound primary key for the table, because Django does not support that. Is there a way I can get a validated serializer to do the logic I described above, or is there a better way? (I am also thinking of trying to create and updating in except, but so far it looks a but cumbersome. -
Django formsets... bound, request,... coding pattern?
I am currently going through the base django documentation as I am trying to come up with some basic edit view class for an old project of mine. For this I have to work with formsets. I am confused at the pattern of calls used within this example for producing an edit view. What is the exact reason why you have to instantiate the formset for the validation with the request.POST, and for errors you recreate the whole thing again with your initial instance... (Otherwise it won't show any data) def manage_books(request, author_id): author = Author.objects.get(pk=author_id) BookInlineFormSet = inlineformset_factory(Author, Book, fields=('title',)) if request.method == "POST": formset = BookInlineFormSet(request.POST, request.FILES, instance=author) if formset.is_valid(): formset.save() # Do something. Should generally end with a redirect. For example: return HttpResponseRedirect(author.get_absolute_url()) else: formset = BookInlineFormSet(instance=author) return render(request, 'manage_books.html', {'formset': formset}) -
Windows/Python Error WindowsError: [Error 3] The system cannot find the path specified
Hi I am new to python and i need some help. I trying to run a file on Windows 10 OS with python 2.7. import os import re import codecs import numpy as np import theano models_path = "./models" eval_path = "./evaluation" eval_temp = os.path.join(eval_path, "temp") eval_script = os.path.join(eval_path, "conlleval") def get_name(parameters): """ Generate a model name from its parameters. """ l = [] for k, v in parameters.items(): if type(v) is str and "/" in v: l.append((k, v[::-1][:v[::-1].index('/')][::-1])) else: l.append((k, v)) name = ",".join(["%s=%s" % (k, str(v).replace(',', '')) for k, v in l]) return "".join(i for i in name if i not in "\/:*?<>|") def set_values(name, param, pretrained): """ Initialize a network parameter with pretrained values. We check that sizes are compatible. """ param_value = param.get_value() if pretrained.size != param_value.size: raise Exception( "Size mismatch for parameter %s. Expected %i, found %i." % (name, param_value.size, pretrained.size) ) param.set_value(np.reshape( pretrained, param_value.shape ).astype(np.float32)) def shared(shape, name): """ Create a shared object of a numpy array. """ if len(shape) == 1: value = np.zeros(shape) # bias are initialized with zeros else: drange = np.sqrt(6. / (np.sum(shape))) value = drange * np.random.uniform(low=-1.0, high=1.0, size=shape) return theano.shared(value=value.astype(theano.config.floatX), name=name) def create_dico(item_list): """ Create a dictionary of … -
Is there any method to set default value form.charField()?
I have created a form to take input from an HTML page like given bellow: class In_Form(forms.Form): Input_peptide = forms.CharField(label='Start Year ', max_length=100) sites_to_be_muted = forms.CharField(label='End Year', max_length=100) Amino_acide = forms.CharField(label='End Year ', max_length=100,) Is there any method through which I can set a default value for html form. I have tried "initial" but its not working in my case: please help -
404 Not found error in suds request send - python - django
I'm setting up online payment portal to my website. I use below code: from suds.client import Client # Within a function: ZARINPAL_WEBSERVICE = 'https://www.zarinpal.com/pg/services/WebGate/wsdl' amount = 20000 MERCHANT_ID = 'blah-blah-blah' description = 'TEST DESCRIPTION' # Required email = form.cleaned_data.get('email') # Optional mobile = form.cleaned_data.get('phone') # Optional CallbackURL = 'http://127.0.0.1:8000/business/verify/' client = Client(ZARINPAL_WEBSERVICE) print("###########################################################") result = client.service.PaymentRequest(MERCHANT_ID, amount, description, email, mobile, CallbackURL) if result.Status == 100: return redirect('https://www.zarinpal.com/pg/StartPay/' + result.Authority) else: return HttpResponse('Error') But before it shows me payment gate, it generates an error: Exception at /business/upgrade/ (404, 'Not Found') Request Method: POST Request URL: http://localhost:8000/business/upgrade/ Django Version: 1.11.4 Exception Type: Exception Exception Value: (404, 'Not Found') and the error is for this line of code: result = client.service.PaymentRequest(MERCHANT_ID, amount, description, email, mobile, CallbackURL) What's the problem? and how can I solve that? thanks -
Many-to-many relationships with several fields in Django
I have the following model: class Trip(models.Model): driver = models.ForeignKey(User) trip_cost = models.IntegerField(blank=True, null=True) passenger = models.CharField(max_length=50, blank=True, null=True) shared_cost = models.IntegerField(default=0, blank=True, null=True) Each Trip can have a driver alone, or a driver with several passenger. For each passenger the driver can set the percentage of the trip_cost each passenger is going to pay. What I need is to have: the field passenger to be listing all Users several passenger + shared_cost for each Trip. I guess I should use Many-to-many but I cannot make it work. Also when I try to set the passenger to models.ForeignKey(User), I get an error. Any help or direction highly appreciated. -
How to use custom variables in serializers?
I want to create a serializer that uses the variables from my model and also counts how many data of the same id is found in the table. I have created this, but it doesn't work: class WebsiteSerializer(serializers.Serializer): item_nr = serializers.IntegerField() class Meta: model = URL fields = ( "id", "item", "status", "item_nr " ) def get_item_nr (self, obj): obj.item_nr = Items.objects.filter(item_id=self.context.get(id)).count() return obj.item_nr -
Django Authenticate returns None with correct username and password during Userlogin
My User login has some issue with the authentication process. this is my code repository user = authenticate(username=username, password=password) returns user as none This is how my Accounts/views.py looks for login def login_view(request): params = {} params.update(csrf(request)) if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') # First get the username and password supplied # username = request.POST.get('username', '') # password = request.POST.get('password', '') # Django's built-in authentication function: print(username, password) user = authenticate(username=username, password=password) print('after aunthenticate', user) # If we have a user if user: # Check it the account is active if user.is_active: # Log the user in. login(request, username) # Send the user back to some page. # In this case their homepage. # return HttpResponseRedirect(reverse('/user_login/')) return render_to_response('user_login.html', RequestContext(request, {})) else: # If account is not active: return HttpResponse("Your account is not active.") else: print("Someone tried to login and failed.") print("They used username: {} and password: {}".format(username, password)) return HttpResponse("Invalid login details supplied.") else: form = LoginForm() args = {'form': form} head_list.update(args) # Nothing has been provided for username or password. return render(request, 'login.html', head_list) the login.html page is shown below {% block content %} <section class="container"> <h1>LiquorApp Login Console</h1> <div … -
ImportError: cannot import name patterns in django application
I am trying to create a facebook extractor for my research. for the purpose I have tried many libraries, but could not find an example. lastly I have reached this repository, which I guess is what I was looking for. But the problem is when I ran the it, I cam e across the following error: Performing system checks... Unhandled exception in thread started by <function wrapper at 0x0000000004540518> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\lenovo-pc\Desktop\psa-allauth-master\example\urls.py", line 1, in <module> from django.conf.urls import patterns, include, url ImportError: … -
Django How do you information from another model in a view?
I think this question has been asked a few times already, however, the questions and their answers are not that clear. If you can make the headline question or the example below to be clearer. Please do. Example: I have an orchard, within my orchard I have fields of apple trees and these apple trees have apples. The question is using my models: how do I get the number of apples in a given field? total mass of all the apples produced in that given field? Model class Field(models.Model): size = models.PositiveIntergerField() max_tree_number = models.PositiveIntergerField() class Tree(models.Model): field = models.ForeignKey(Field) age = models.PositiveIntergerField() variety = models.CharField(max_length=200) class Apple(models.Model): tree = models.ForeignKey(Tree) mass = models.PositiveIntergerField() View class FieldView(generic.ListView): template = '[app_name]/index.html' def get_context_data(self, **kwargs): context = super(FieldView, self).get_context_data(**kwargs) context['tree_count'] = Field._meta.model_name context['mass'] = ??? context['apple_count'] = ??? Thank you for your time -
nginx 104: Connection reset by peer while proxying upgraded connection
nginx: *106 recv() failed (104: Connection reset by peer) while proxying upgraded connection, For my chat on django 1.11, I use django-channels, duphne, nginx and nginx to fill in the log with this error. Because of this I can not keep track of who has the socket open. duphne start command: daphne -b 0.0.0.0 -p 8001 .asgi:channel_layer help me to fix this please server { listen 80; server_name <server_name>; access_log /path/to/log/access-nginx.log; error_log /path/to/log/error-nginx.log; client_max_body_size 20M; location / { proxy_pass http://0.0.0.0:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; 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-Host $server_name; } location /static { root /static/path; } location /media { root /media/path; } } -
Django - Save variable to CharField
I want to save a variable to CharField in my models.py. Here is some code: models.py class Profile(models.Model): user = models.OneToOneField(User, related_name='user') oceny = models.CharField(max_length=150, default='') updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username Here is my variable oceny = lib.oceny_skon and the result of it: [1, 4, 5.75, 2] How can I save this to oceny field ? Thanks for help ! -
Unresolved Reference in view.py when calling from model.py in Django
Im just trying to learn Django and i've just been following youtube tutorials but i've encountered a problem when i was making a basic web app. Here's the code from views.py from django.http import HttpResponse from .models import machine def equipment_index(request): all_machines = machine.objects.all() html='' for machine in all_machines: url='/equipment/' + str(machine.id) + '/' html+='<a href="'+url+'">'+machine.name+'</a><br>' return HttpResponse(html) def detail(request, machine_id): return HttpResponse("<h2>Details for machine id: "+ str(machine_id)+"</h2>") And this is the code from models.py from django.db import models # Create your models here. class machine(models.Model): brand = models.CharField(max_length=20) name = models.CharField(max_length=50) acquisition_cost = models.DecimalField(max_digits=12, decimal_places=2) details = models.CharField(max_length=2000) TYPE_CODES = ( ('AC', 'Air Compressor'), ('BL', 'Backhoe Loader'), ('BR', 'Breaker'), ('BD', 'Bulldozer'), ('OT', 'Other'), ) type = models.CharField(max_length=2, choices=TYPE_CODES) def __str__(self): return self.name + ' - ' + self.brand There is an 'Unresolved Reference' under 'machine' in machine.objects.all() I followed everything in the tutorial videos exactly but it still has an error -
Enable search in modelviewset django
How do I enable search in this modelviewset? class AuthorViewSet(viewsets.ModelViewSet): queryset = models.Author.objects.all() serializer_class = serializers.AuthorSerializer permission_classes = [CreatePutDeleteAdminOnly] pagination_class = StandardResultsSetPagination filter_backends = (SearchFilter, DjangoFilterBackend, OrderingFilter) ordering = ('-pk',) search_fields = ('title',) I want 127.0.0.1:8000/api/v1/category/?search=j to return only the categories that start with j. -
django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
when I used command "python manage.py makemigrations"(the same with typing "python manage.py runserver"),it threw this error.And then I checked the authority of the users. The code and result are as fllows. mysql> select host,user from mysql.user; +-----------+---------------+ | host | user | +-----------+---------------+ | % | root | | % | zhuxin | | localhost | mysql.session | | localhost | mysql.sys | | localhost | root | | localhost | zhuxin | +-----------+---------------+ mysql> show grants for 'zhuxin'@'%'; +---------------------------------------------------------------+ | Grants for zhuxin@% | +---------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'zhuxin'@'%' WITH GRANT OPTION | | GRANT ALL PRIVILEGES ON `blogdb`.* TO 'zhuxin'@'%' | +---------------------------------------------------------------+ mysql> show grants for 'root'@'%'; +--------------------------------------------------+ | Grants for root@% | +--------------------------------------------------+ | GRANT USAGE ON *.* TO 'root'@'%' | | GRANT ALL PRIVILEGES ON `blogdb`.* TO 'root'@'%' | +--------------------------------------------------+ I have tried everything to solve it, but for no use. -
History Of Django Naming
Why Django web framework described as “developed in a newsroom”. Is it because the project was started at Lawrence Journal-World newspaper in 2003? and then why it is named as Django (name of guitarist)? -
Django & Socket Server: Can I add socket server instance to "memory"?
I'm working with: Django 1.11 Python Sockets I have a Socket server like this: class SocketServer(threading.Thread): def __init__(self, ip="127.0.0.1", port=5000, _buffer=1024): super(RoomSocketServer, self).__init__() self.IP = ip self.PORT = port self.RECV_BUFFER = _buffer # Advisable to keep it as an exponent of 2 self.CONNECTION_LIST = [] # list of socket clients self.MESSAGE_QUEUES = {} # List of message queue by socket self.OUTPUTS = [] self.SERVER = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # this has no effect, why ? self.SERVER.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.SERVER.bind((self.IP, self.PORT)) self.SERVER.listen(10) # Add server socket to the list of readable connections self.CONNECTION_LIST.append(self.SERVER) self.ROOM = Room.objects.create(port=port, ip=ip, type_room=type_room) def read_sockets(self, read_sockets): ''' ... ''' def write_sockets(self, write_sockets): ''' ... ''' def error_sockets(self, error_sockets): ''' ... ''' def run(self): while 1: # Get the list sockets which are ready to be read through select read_sockets, write_sockets, error_sockets = select.select(self.CONNECTION_LIST, self.OUTPUTS, []) # Read sockets self.read_sockets(read_sockets) self.write_sockets(write_sockets) self.error_sockets(error_sockets) self.SERVER.close() I can run this SocketServer like this anywhere on Django (custom_command, a view, celery...): from socket_server import SocketServer socket_server = SocketServer() socket_server.start() # And the code continues while the socket server is running # I would like to save socket_server instance anywhere to access # Later from anywhere or trigger a signal to finish it … -
How to set python3 in Django?
I would like to know how to setup Django with Python3.X All of my Django Projects was in python2.X taken by system default.. I knew in Django 2.0 onwards, Django will going to support only Python3 Environment. so i decided to test my Django Apps in Python3.. is there a way to change or define Python3 Environment in Django Apps? -
uwsgi can't load app when set up nginx+django service on centos
centos7, python3.6.3,django1.11, uwsgi2.0.15 when i run command 'uwsgi --ini djcode_uwsgi.ini', no app is loaded,the message is as below: [uWSGI] getting INI configuration from djcode_uwsgi.ini > open("/usr/lib64/uwsgi/python3_plugin.so"): No such file or directory > [core/utils.c line 3686] !!! UNABLE to load uWSGI plugin: > /usr/lib64/uwsgi/python3_plugin.so: cannot open shared object file: No > such file or directory !!! > *** Starting uWSGI 2.0.15 (64bit) on [Sat Oct 7 16:47:06 2017] *** compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-11) on 19 May > 2017 14:33:49 os: Linux-3.10.0-514.26.2.el7.x86_64 #1 SMP Tue Jul 4 > 15:04:05 UTC 2017 nodename: izuf64a9gck8o1inxenp1cz machine: x86_64 > clock source: unix pcre jit disabled detected number of CPU cores: 1 > current working directory: /home/djcode detected binary path: > /usr/sbin/uwsgi uWSGI running as root, you can use > --uid/--gid/--chroot options > *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** chdir() to /home/djcode your processes number limit is 3889 your memory page size is 4096 bytes detected max file descriptor number: > 65535 lock engine: pthread robust mutexes thunder lock: disabled (you > can enable it with --thunder-lock) uwsgi socket 0 bound to TCP address > :8001 fd 3 your server socket listen backlog is … -
ImportError: No module named 'social_django'
Everytim I am running teh application from the Github Repository, I am getting the following error: Traceback (most recent call last): File "C:/Users/lenovo-pc/Desktop/Django-Social-Authentication-master/socialauth/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python35\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python35\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Python35\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python35\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Python35\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'social_django' I want to know what is this: social_django all about? I have intsall many libraries, but non of then have satisfied this error: python-social-auth[django] social-auth-app-django But nothing happens. Please let me know what I should do. -
django form data not saved in database
I have a form to make POST data to database. I'm using Django 1.11 views.py class BusinessCreate(CreateView): model = Business fields = '__all__' @method_decorator(login_required) def dispatch(self, *args, **kwargs): messages.success(self.request, 'dispatch') return super(BusinessCreate, self).dispatch(*args, **kwargs) def form_valid(self, form): messages.success(self.request, 'valid') form.instance.user = self.request.user # set user_id field to session user form.save() def get_success_url(self): messages.success(self.request, 'Business Added Successfully') return reverse('business:list') template <form class="card" method="POST"> {% csrf_token %} {{ form.non_field_errors }} {{ form.non_field_errors }} {% render_field form.name class='form-control' placeholder='Business Title' %} {{ form.name.errors }} {% render_field form.business_type class='form-control' %} {{ form.business_type.errors }} <button class="btn">Add Business</button> </form> When I submit the form, it doesn't save and also does not return any error. The messages in three methods in views.py are to check which method is called and it always prints dispatch since the only dispatch is called. I used debug_toolbar to check for debug whether request is POST or GET or none of the two and it show. -
Manipulating data passing from database to template (Django)
I'm still pretty new to Django, so I really hope I can explain what I need to do. I have a form where users input information about a character and then it's stored in the database and displayed for them on a page. I know it's easy to recall and display this data with template variable call (i.e. {{character.gender}}), however, I am trying to use the inputted data to create other variables based on the data BEFORE it goes into the template. I've done this in visual basic before and essentially used an if statement to create a new variable to store the information before passing it back out, but I can't figure out how to do this with django/python. For example, if the user provided the following information: Name = "Jill" Age = 23 Gender = "Female" I'd want to be able to do something like: if gender = "female": gender_identifier = 'she' if age < 30: youth = "is still very young" and then be able to do something like this in a template: {{character.name}} is {{character.age}} years old and {{gender_identifier}} {{youth}}! to output "Jill is 23 years old and she is still very young!" What I"m struggling … -
How do i show an active link in a django navigation bar dropdown list?
I have a navbar menu with a list of links which i want to show the active link when the user is on the page, so far i have managed to do this with links that dont have dropdowns like this. But I cannot seem to get it right with the dropdown links in such a way that if the user is on a page on the dropdown link the parent link on the navbar gets highlighted.like shown below Any help would be greatly appreciated. -
Identify type of logged in user
I have a custom user setup like this: class CustomUser(AbstractUser): pass class Employee(CustomUser): user = models.OneToOneField(settings.AUTH_USER_MODEL) # other fields In settings.py, I then add the following key: AUTH_USER_MODEL = 'myapp.CustomUser' I want to identify who logged in redirect them to appropriate views or urls. In my account activation view, after the logging them in I redirect them to their appropriate page like this if hasattr(user, 'employee'): return redirect('edit_employee', slug=user.employee.slug) else: return redirect('index') But this doesn't feel that right as I need to use this in other places like showing a different profile page link in the templates. How do I better identify the regular user and employee in views and templates? -
Javascript search filter on user generated table from Django
I'm trying to create a dynamic search engine with javascript from a user generated table that is created with a form that adds a song to the table. I want to search the list that's already created. It's not doing anything when I type in anything and no errors in the DOM. Can some someone tell me where i went wrong? Here's my HTML: {% extends "base.html" %} {% load static %} {% block title %}My Song List{% endblock %} {% block content %} <input type="text" name="search" placeholder="Search by Title" class="animated-search-form" id="myInput onkeyup="search();"> <div class="translucent-form-overlay"> <form action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Add Song" /> </form> </div> <div id="list-container"> <h1 style="text-decoration:underline">Sorted Alphabetically by Song Title</h1> <h5> <table id="myList"> {% for song in song_list %} //song_list is the model <tr> <td>Title: {{song.title}}</td> <td>Artist: {{song.artist}}</td> <td>Year: {{song.year}}</td> <td>Genre: {{song.genre}}</td></tr> {% endfor %} </table> </h5> </div> {% endblock %} And here's my javascript: function myFunction() { // Declare variables var input, filter, table, tr, td, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myList"); tr = table.getElementsByTagName("tr"); // Loop through all table rows, and hide those who don't match the search query for (i = 0; i < …