Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Application Architecture
Hi Guys I would like your advice on a new app that I intend to create with Django. I am quite new as a Full Stack developer lacking in experience on how to structure properly my project and espacially the registration part My app is the following. It is like a survey app, where on one side you have the "Company area", that create the forms questions and on the other side the "candidate area" where they get the form survey and can answer it. My question is the following: 1) Should I create on app with one registration for every one ? using the User model provided by Django, or 2) Create two different apps with two different registrations, if yes since I cannot user the User model provided by django for everyone how do I create two new authentication users such as CompanyUsers and CandidateUsers ? I cannot do it from the admin panel .. Thx you very much ;)) -
Django: is it possible to perform queries on a cached QuerySet instead of querying the database?
I often need to cache results and perform ORM-like operations but with normal Python logic because I don't want the database to be hit due to performance issues. For this very reason I wonder if Django offers a way of performing ORM operations on a cached QuerySet, instead of querying the database every single time the core query we are using changes slightly. To visualize what I am saying, let's say we have these different queries: # when evaluated it hits the db devs = Worker.objects.filter(job__category=JobCategory.DEVELOPER) # when evaluated it hits the db again young_devs_salary = devs.filter(dob__gte=datetime.now() - relativedelta(years=24)).values('dob', 'salary') # it would hit the db again wellpaid_devs = devs.filter(salary__gte=high_salary_yearly) Note that the first QuerySet would be sort of a superset of the rest of the following QuerySets. What I am after is figuring out a way to tell Django that only the very first query, devs, should hit the db, and then cache its results, while the other queries, which use devs, should not query the database but the cached QuerySet instead. Is this possible? And if Django does not support this, why? Maybe my scenario is not that common? But somewhat I doubt it, because I stumble upon … -
Django reverse foreignkey query in template using _set
Dear Slack community. given my simplified models: * classes: name_id; description; * architectures: name_id; description; * families: name_id; description; architecture = foreignKey(architectures); class = foreignKey(classes); I'm trying to get from a query defined in views.py as: query = classes.objects.all() return(query) the number of architectures entry related to it in templates. {% for obj in query %} Class {{ obj.name_id }} has {{ obj.families_set.all.architecture.count }} architectures. {% endfor %} But nothing is shown. If I try to do {{ obj.families_set.all.count}} I have all the number of families in the class. If I try to do {{ obj.families_set.all.o.architecture.name_id }} I get the first name of architecture that belongs to the class. Can someone help? I don't understand what I'm doing wrong. -
Celery canvas group of chains passing too many arguments to constituent tasks
I am encountering some very strange behavior with the following sort of celery workflow: workflow = group( chain(task1.s(), task2.s()), chain(task3.s(), task4.s()), ) This is in the context of django. When I call the workflow as follows: workflow.apply_async((n,)) ...for any integer value of n, the first task in each chain (task1 and task3) will fail with a TypeError like the following (taken from celery events): args: [9, 8, 7, 5, 4, 3] kwargs: {} retries: 0 exception: TypeError('task1() takes exactly 1 argument (6 given)',) state: FAILURE The arguments after the first are always arguments that the workflow was previously called with. So, in this example, I have called workflow.apply_async((9,)), on this occasion, and the other numbers are values that were passed on previous occasions. On each occasion, the erronious arguments passed to task1 and task3 will be the same. I'm tempted to post this as a bug report to celery, but I'm not yet certain the mistake isn't mine in some way. Things I have ruled out: I'm definitely passing the arguments I think I am passing to workflow.apply_async. I have separately constructed and logged the tuple that I pass, to make sure of this. It isn't anything to do with … -
Is it magic in Celery using Docker?
I have a project with two services on django and flask Some requests require the execution of heavy asynchronous tasks. I already used earlier Celery + Django with Redis as broker. It's needed for run the task on schedule. But.. I can not understand how it works inside Docker containers Let's say there are 3 containers: - django_web - redis - celery_worker django_web and celery_worker use redis as a broker. Tasks are defined in the container django_web How does the Celery worker in the celery_worker container perform the task? The container with the worker does not have access to the function and operations. Is all the contents of the task somehow transmitted through a broker and it does not matter where the code is located? Or is only the name and function signature passed? I can not find best practice how to use Celery in Docker containers -
Admins, users and groups in different organizations in Django
I'm creating a Django app, aimed at organizations that will have several users. So in the models, I have organizations and users, and organizations should be independant. First user of an organization to signup will be admin, next users to signup will be employees. Admin can create user groups (usergroups/roles) to set the employees' permissions within the app. Django already allows this, but a Django admin can edit all users right? Is there a way to have a manager by organization, who could only see and edit its employees permissions and not see all the users in database? -
Output calculations to template
I want to perform row level math on a model and display the results in the template. The database has a row for each company per day. class MyModel(models.Model): company = model.CharField(... daily_target = model.PositiveSmallIntger(... actual = model.PositiveSmallIntger(... date = model.DateField(... In the template I'd want to display the result of 100 * actual / daily_target for the logged-in company. I have no problem doing this in the python interpreter but am confused about how to do this with views & templates. -
Multi select list box with static values in Django with filter_horizontal
I am new in Django and I am loving it. What I have I have created a category listing in django admin where the admin can create categories and assign multiple categories to a user.I am using ManyToManyField What I want to do Instead of creating categories manually, I want that multi select box to read a text file(categories are listed there) and list all the categories. Is it at all possible with using filter_horizontal. If yes then I would like to start by using some static options/choices and my next step would be reading the values from text file. accounts/models.py class Category(models.Model): category_name = models.CharField(max_length=150, blank=False, null=True, default="") module_name = models.TextField(blank=False, null=True) def __str__(self): return self.category_name class Meta: verbose_name_plural = "categories" class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name ='profile') email_confirmed = models.BooleanField(default=False) phone_number = PhoneNumberField( blank=True, null=True) organisation = models.CharField(max_length=30, blank=True) category = models.ManyToManyField(Category) accounts/admin.py class ProfileInline(admin.StackedInline): model = Profile filter_horizontal = ('category',) class categoryAdmin(admin.ModelAdmin): pass admin.site.register(Category, categoryAdmin) I was going through this SO thread - django model choice option as a multi select box But I don't know how MultipleChoiceField will relate with filter_horizontal Any help/suggestion is highly appreciated. Thanks in advance. -
django login with plain password
I had a db with usernames and password(plain text) and now I have to create an app of login. How can i create a login ? Can I use django registration or any other django default apps of login which makes my work easy. What I had been tried is I had created a duplicate table and tried to encrypt it with this code but it didn't work import crypt # To encrypt the password. This creates a password hash with a random salt. password_hash = crypt.crypt(password) # To check the password. valid_password = crypt.crypt(cleartext, password_hash) == password_hash -
Serve dynamically generated xml file to download in Django with character encoding information
I need to generate a XML file dynamically in Django to download. I can do this with the code below, but without the character encoding information: import xml.etree.ElementTree as ET def get_xml(): my_xml = ET.Element('foo', attrib={'bar': 'bla'}) my_str = ET.tostring(my_xml, 'utf-8', short_empty_elements=False) return my_str.decode('utf-8') # my view def download_xml_file(request): response = HttpResponse(get_xml(), content_type="application/xml") response['Content-Disposition'] = 'inline; filename=myfile.xml' return response I can add the character encoding information with the code below, but writing in a file in the server first: def get_xml(): my_xml = ET.Element('foo', attrib={'bar': 'bla'}) tree = ET.ElementTree(my_xml) fname = 'myfile.xml' tree.write(fname, xml_declaration=True, encoding='utf-8') with open(fname, 'r') as fh: my_str = fh.read() return my_str How do I serve the xml file to download with character encoding information without writing in the server first? -
How to pass data from SelectDateWidget to view and url
I have a problem how to pass selected data from SelectDateWidget to view and to url. Now I have the hardcoded data get_success_url in the digest, after the "submit" on the form. For the SelectDateWidget help, I want to select the month and year for which I want to show selected events. Here is my form: class BookingForm(forms.ModelForm): date_start = forms.DateField(widget=SelectDateWidget(years=range(1980, 2018))) class Meta: model = Booking fields = ('date_start', ) widgets = {'date_start': SelectDateWidget()} This is my view, where I have hardcoded value for success url: class BookingListView(ListView, FormView): model = models.Booking form_class = BookingForm queryset = models.Booking.objects.all() # order_by('-date_start') paginate_by = 80 template_name = 'events/archive_list.html' context_object_name = 'object_list' date_field = 'date_start' allow_future = True def get_context_data(self, **kwargs): context = super(BookingListView, self).get_context_data(**kwargs) context['mode'] = 'archive' context['form'] = BookingForm() return context def get_success_url(self): return reverse('archive:archive_month_numeric', kwargs={'year': 2014, 'month': 10}) My url to page where I have events in selected date: url(r'^/(?P<year>[0-9]{4})/(?P<month>[0-9]+)/$', views.ArticleMonthArchiveView.as_view(month_format='%m'), name="archive_month_numeric"), -
Unable to connect to MongoDB from a Django containorized app
I'm writing an application with django and I want to use mongoDB as my database. But I am unable to connect to it. The error I get is: ConnectionFailure: [Errno 111] Connection refused My settings for Connection are: import mongoengine _MONGODB_USER = 'root' _MONGODB_PASSWD = '12345' _MONGODB_HOST = '192.168.8.101' _MONGODB_NAME = 'admin' _MONGODB_DATABASE_HOST = \ 'mongodb://%s:%s@%s/%s' \ % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME) mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST) What am I doing wrong? Any help would be appreciated -
Filtering out the Users if Conversation occurred
Here's my Model class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() How can I filter out the Users only if, either Current User have sent them a message or they have sent Current User a message, as we see on our Social Networks. Please help me with this code. Thanks in advance! -
UPPER_CASE_WITH_UNDERSCORES in Django
in Django, almost all the variables' naming style is UPPER_CASE_WITH_UNDERSCORES, for instance: INSTALLED_APPS = [ ] MIDDLEWARE_CLASSES = [ ] and so on... what's the conventions it follows? -
model choices - invalid keyword argument for this function
I have an intractable problem driving me round the bend (arg!) I suspect the problem is that my model uses a choices argument for one field - am I assigning to it incorrectly? model: class Attempt(models.Model): # User attempt and results at a question # Records their result, points to an Entry related to what they typed, records the user, ELO and variance at time CORRECT = 'C' WRONG = 'W' REPORT = 'R' A_TYPE_CHOICES = ((CORRECT, 'Right'), (WRONG, 'Wrong'), (REPORT, 'There is a problem with the question')) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) entry = models.ForeignKey('Entry', on_delete=models.CASCADE) assesment = models.CharField(max_length=1,choices=A_TYPE_CHOICES, db_index=True) feedback = models.CharField(max_length=200, help_text="What is it about the question that makes it unclear or misleading",blank=True) score = models.FloatField(null=True, blank=True, help_text="score of the user when this attempt was made - only recorded if variance below a certain threshold, otherwise null") variance = models.FloatField() created = models.DateTimeField(auto_now=True) call to it in views: Attempt.objects.create(user=request.user, entry=Entry.objects.get(id=request.POST['entry_id']), assessment=request.POST['self_assessment'], feedback=request.POST['feedback'], score=sp.score, variance=sp.variance, ) request.POST['self_assessment'] is equal to a string of either 'C','W', or 'R'. The error I receive is: File "C:\Users\Win7\OneDrive\Programming\Git\lang\Quiz\views\assessment.py", line 174, in question_score variance=sp.variance, File "C:\Users\Win7\OneDrive\Programming\VirtualEnvs\lang\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Win7\OneDrive\Programming\VirtualEnvs\lang\lib\site-packages\django\db\models\query.py", line 392, in create obj = self.model(**kwargs) … -
No module named django.conf
I am trying to restart django process on my server using this command: gunicorn projectname.wsgi However, I keep getting this error: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 122, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 130, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 366, in import_app __import__(module) File "/root/xxxx/xxxxxxx/xxxx/wsgi.py", line 11, in <module> from whitenoise.django import DjangoWhiteNoise File "/usr/local/lib/python2.7/dist-packages/whitenoise/django.py", line 5, in <module> from django.conf import settings ImportError: No module named django.conf any idea where to go from there? -
Adding additional data in the DRF api endpoint
My endpoints.py have: from wagtail.api.v2.endpoints import BaseAPIEndpoint from .models import Week, Ingredient, Menu class WeekAPIEndpoint(BaseAPIEndpoint): model = Week def register_endpoints(api_router): api_router.register_endpoint('week', WeekAPIEndpoint) And if I follow the link 127.0.0.1:8000/api/v2/week i get this: Is it possible to raise data by one step in DRF endpoints? from here 127.0.0.1:8000/api/v2/week/1: I opened issue in my github. Didn't want to create too big a question here. -
unable to build docker-compose build
I'm getting this error when I tried to docker-compose build my docker-compose.yml file: In file './docker-compose.yml' service 'version' doesn't have any configuration options. All top level keys in your docker-compose.yml must map to a dictionary of configuration options. docker version Client: Version: 1.12.6 API version: 1.24 Go version: go1.6.3 Git commit: 78d1802 Built: Tue Jan 31 23:47:34 2017 OS/Arch: linux/amd64 Server: Version: 1.12.6 API version: 1.24 Go version: go1.6.3 Git commit: 78d1802 Built: Tue Jan 31 23:47:34 2017 OS/Arch: linux/amd64 docker --version Docker version 1.12.6, build 78d1802 docker-compose --version docker-compose version 1.5.2, build unknown is this because the build unknown? -
How to add forgot password link on this from in django admin login? I am new in djnago, users please help me
How to add forgot password link on this from in django admin login? I am new in djnago, users please help me. -
Django test Client can only login once?
Our team is currently writing tests for our application. I am currently writing code to acces the views. These views are behind a login-screen, so our test first have to login and than peform the rest of the test. I've run into a very strange error. Basically My tests can only login once. As you can see in the example below, both classes are doing the exact same thing, yet only one of them succeeds with the login, the other gives a '302 doest not equal 200' assertion error. If I comment out the bottom one, the one at the top works, and vice versa. Code that is testing different views also doesnt work, unless I comment out all other tests. It doesnt matter if I login like shown below, or use a different variant (like self.client.login(username='test', password='password')). Me and my team have no idea why Django is behaving this way and what we are doing wrong. Its almost as if the connection remains open and we would have to add code to close it. But the django-documentation doesnt mention any of this. DOes anyone know what we are doing wrong? class FunctieListView_tests(TestCase): """Function listview only shows the data for … -
How to config initial connection command for Django databases?
Can I do something like this in Django settings file: DATABASE = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.sqlite3', 'INITIAL_CMD': 'PRAGMA journal_mode=WAL', # here } } so that whenever Django connects to default DB, it issues PRAGMA journal_mode=WAL first before others. And yes, for those familiar with PHP, I need something like MYSQL_ATTR_INIT_COMMAND in MySQL PDO -
Django multiple Foreign Key in one model
My name is Raphael I am very new to programation and django in general and I am creating a Human Ressources project with 3 apps 'main website', 'CandidatePart', 'CompanyPart'. I am having difficulties to structure my models which are now the following: CompanyPart: class Company(models.Model): company_name = models.CharField(max_length = 250) def __str__(self): return self.company_name class Team(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) team_name = models.CharField(max_length = 500) def __str__(self): return self.team_name class TeamMember(models.Model): team = models.ManyToManyField(Team) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) position = models.CharField(max_length=150,default='') def __str__(self): return self.first_name + ' ' + self.last_name + ' as ' + self.position class HR_member(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) def __str__(self): return self.first_name + ' ' + self.last_name CandidatePart: class Candidate(models.Model): HR = models.ForeignKey('CompanyPart.HR_member') company = models.ForeignKey('CompanyPart.company', default = '') first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.EmailField() As you can see I setup two foreignkeys to be able to access HR and company The problem is that I would like when choosing a company to have access only to the HR related to that company or if I select an HR to select automatically the company related to. I hope I was clear enough, thank you very … -
How can I create simple Django chat based on WebSockets with PostgreSQL database?
I try to create Django backed using WebSockets in accordance with Django documentation. I would like to receive message, save it to my PostgreSQL database and send response to the same user. At this moment message may be the same as received. I try to do it in the way shown below, but I get: django_1 | 2017-08-31 08:30:52,050 - ERROR - worker - Error processing message with consumer backend.consumers.msg_consumer: django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.6/site-packages/channels/worker.py", line 119, in run django_1 | consumer(message, **kwargs) django_1 | File "/code/backend/consumers.py", line 11, in msg_consumer django_1 | message=message.content['message'], django_1 | KeyError: 'message' routing.py: from channels.routing import route from backend.consumers import ws_connect, ws_receive, ws_disconnect, msg_consumer channel_routing = [ route("websocket.connect", ws_connect), route("websocket.receive", ws_receive), route("websocket.disconnect", ws_disconnect), route("chat", msg_consumer), ] models.py: from django.db import models class Message(models.Model): message = models.CharField(max_length=200) consumers.py: from channels import Group from .models import Message from channels import Channel # Connected to chat-messages def msg_consumer(message): # Save to model Message.objects.create( message=message.content['message'], ) # Broadcast to listening sockets Group("chat").send({ "text": message.content['message'], }) # Connected to websocket.connect def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) # Connected to websocket.receive def ws_receive(message): Channel("chat").send({ "text": … -
Django: the current state of the database isn't present in the clean method
I want to test validation during creation of new Name. I have following models: class Project(models.Model): name = models.CharField(max_length=100, unique=True) class Name(models.Model): name = models.SlugField(max_length=100) project = models.ForeignKey( Project, null=True, on_delete=models.DO_NOTHING, related_name="names") def clean(self): """ Ensure that self.name is unique for a given project. If not, raise ValidationError. """ names = [name.name for name in self.project.names.all()] if self.name in names: raise ValidationError( {"name": _("Such name already exists in this project")}) In my test I do the following: Create testing project like this: proj = Project.objects.create(name="test_proj") Create pre-existing name like this: Name.objects.create(name="pre_name", project= proj) Send request to view, which create new Name and call validation. My test debug print output shows the following: Project id in test: 1 Project name set in test: <QuerySet [<Name: pre_name>]> Project id in clean method: 1 Project name set in clean: <QuerySet []> I dont really understand why names set of test_proj is empty in Name clean method? Thanks in advance! -
How do I add an existing docker image to my dockerfile?
So the docker image I want to add to my dockerfile is on GitHub public repo. if I do FROM vevende/python3:latest how does my dockerfile knows how to fetch that docker image from that repository I'm not even specifying a link to the docker image.