Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializer for ManytoOne relationship not displaying any data
My Models class Conversation(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='conversation_owner') users = models.ManyToManyField(UserProfile, through='CheckUnread') subject = models.CharField(max_length=255) start_date = models.DateField() end_date = models.DateField() class CheckUnread(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) read = models.BooleanField() class Comments(models.Model): name = models.CharField(max_length=255) email = models.EmailField(max_length=255) dateTime = models.DateTimeField() content = models.TextField(max_length=1024) conversation = models.ForeignKey(Conversation, related_name='comments', on_delete=models.CASCADE) My View class MessagingViewSet(viewsets.ModelViewSet): def get_queryset(self): return None def list(self, request): conversations = models.Conversation.objects.using(some_db_name).filter(checkunread__user_id=request.user.id) return Response(self.get_serializer(conversations, many=True).data) My Serializers class CommentSerializer(serializers.ModelSerializer): class Meta: model = models.Comments fields = ('id', 'name', 'email', 'dateTime', 'content', 'conversation_id') class ConversationSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True) class Meta: model = models.Conversation fields = ('id', 'subject', 'start_date', 'end_date', 'owner_id', 'comments') For some reason my response for the view just looks like this [ { "id": 1, "subject": "test", "start_date": "2018-11-11", "end_date": "2019-01-01", "owner_id": 32, "comments": [] },... ] Despite there being comments for the conversations (sample of comments view) [ { "id": 1, "name": "foo", "email": "foo@hotmail.com", "dateTime": "2018-11-11T18:23:44Z", "content": "test comment 1", "conversation_id": 1 },... ] I can't seem to figure out why it's just empty, am I doing something wrong here? I tried removing the related_name and using comments_set but that had the same issue. I feel as if it's something that … -
Different settings.py file for different domains in Django
I have a Django project that will have multiple instances, one for each of my clients, each instance have your own DB and some custom APPs and your own domain, but all share the same source code, the only difference will be the settings.py file pointing for the correct DB. I know I can achieve this using different virtual hosts pointing to different settings using for exemple Apache and WSGI, but in my case I will use AWS Lambda and Zappa to provide this service for my clients. I want to know if exists a way to dynamically load some custom settings depending on the domain that loads the site. -
NoReverseMatch at /guardian/guardianhomepage/
Please feel free too ask more information about this project. What am i doing wrong here .... please help I have provided my models, urls, and views picture with error page picture models urls.py views.py Error -
Django 2 displaying posts by category
In my Django 2.1 app I have the following views: def single(request, post_slug): post = get_object_or_404(Post, slug=post_slug) suggested = Post.objects.all()[:2] context = {'post': post, 'suggested': suggested} return render(request, 'single.html', context) def course(request,post_tags): posts = get_object_or_404(Post, tags=post_tags) posts = Post.objects.filter(is_course=True).filter(tags__contains=post_tags).order_by('lesson_order') return render(request, 'learn.html', {'posts': posts}) and urls.py path('courses/<tag:post_tags/', app.views.course, name='learn'), path( '<slug:post_slug>/', app.views.single, name='single') the single post works fine but courses/tagname doesn't it returns a 404 although I am sure that the tags I am trying to load exist. I think I am making a trivial mistake somewhere! thanks in advance for your help. -
django jquey ajax sends get request with query params instead of post request
My Form post used to work as expected, after some changes it started to send get requests with query params from form input field's data. the question is I need to send FormData. in my javascript file I append all this data and post to the backend. It seems like when doing post request it gets connection refused and makes get request. I have activated csrf token and added LoginRequiredMixin . But event when I am commenting then it still doesnt work. Could you please list me the potential causes. -
How to store a variable history in django?
To simplify my problem, let's say I have a simple User model that happen to have an IntergerField containing a score in a game. I'd like to store the time and the value of the score every time the core is modified. For example, let's say user A starts with score=0 when time=0, then wins 5 points at time=3. I'd change in the view the value of the score, but I'd also like to be able to query another attribute that would give me {0:0, 3:5} The app will need to be used with MySQL, PostgresSQL and probably SQLite -
Which SSO implementation to use?
I tried to implement SSO for a Django web application with OpenID Connect with Keycloak but encountered a roadblock, therefore I'm wondering if OpenID Connect is the right SSO for my use case. What I am trying to achieve: SSO in which there will only be a single identity provider for multiple service provider (web applications) Users cannot self-register a new account. Administrator has to create account for new users. Ability to assign/manage web application specific permissions and roles for users. However, some of the issues I've encountered: Service provider are not aware of existence of a user until the user first logs in to it. E.g. User A is created on Keycloak (Identity Provider) by the Administrator. However, as User A has not yet logged in to Web Application via OpenID Connect, there is no user mapping of User A existing in the Web Application. The problem I faced here is that Adminstrator cannot assign Web Application specific permissions to User A, up until User A first logs in to the Web Application. I want to be able to assign permissions at the point of user creation. I'm wondering if anyone can advise on whether I am using OpenID … -
django userregistration form is not submitting data
I have created user registration form using django form. But its not working. This is how I tried to make this. although If i try to input registered so far this is my code looks like. users/view.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created!!') return redirect('posts-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) users/forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] users/template/register.html {% extends "posts/base.html" %} {% block content %} <div class="content-section"> <form method="POST" action=""> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom md-4">Join Today</legend> {{ form.as_p }} <fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have A Account? <a class="ml-2" href="">Sign In</a> </small> </div> </div> {% endblock content %} -
bootstrap slider with cycle for
Please, help me I have a slider, but i can't use it doesn't work. I think it is because of "active" tag but don't know how to solve it. <div class="carousel-inner"> <div class="carousel-item active"> {% for image_item in product.productimage_set.all %} <img class="d-block w-100" src="{{ image_item.image.url }}"> {% endfor %} </div> </div> -
Django Reservation System
I need to build a web-based reservation system, for example, for a restaurant. Where users will be able to make a table reservation up to a week in advance. This is my first own web project and first-time using Django, so, the idea is that the users/customers can select a table they want to reserve at a particular time, which is then shown as booked during that period. Other users/customers should be able to see when the table is booked and make bookings for when the table is free. I was wondering if I could get any advice on how to approach making something along these lines, the best approach to take? I know this question is extremely vague but any advice would be appreciated! (I am struggling to find similar existing projects) Thanks :) -
Access Dynamic Key in Django For-Loop
I have a list of dictionaries in the following format children = { "1": [ { "id": 0, "name": "one", "parentId": "1" }, { "id": 1, "name": "two", "parentId": "1" } ], "2": [ { "id": 2, "name": "three", "parentId": "2" }, { "id": 3, "name": "four", "parentId": "2" } ] } Within another loop of "parents", I have values like 1 and 2 that I'm trying to use to group. {% for parent in parents %} {% for child in children[parent.id] %} <h1>{% child.name %}</h1> /* other markup */ {% endfor %} {% endfor %} And I am getting an error Could not parse the remainder: '[parent.id]' from 'children[parent.id]' I thought it might be a type issue and it turned out that parent.id is in fact an int, however children[str(parent.id)] yields the same error. What is the proper way to access these dynamic keys? NB: This answer seems to be about how to display it, and does not show how to use the value in a loop. -
Django query an object only if all ManyToMany fields match dict
I am attempting to create a screener test where the user is matched only with programs for which they meet all requirements. The user's input is a dictionary, for example: user_dict = [{location: CA, gender: male, skill: crafts}] The programs have requirements as shown in the models below: class Program(models.Model): name = models.CharField() requirements = models.ManyToManyField("Requirement") class Requirement(models.Model): name = models.CharField() status = models.CharField() I would like the query to retrieve all programs for which all their associated requirements are met. For example, if a program called camp counselor only has the following 2 requirements associated with it: [{'name': 'location', 'status': 'CA'}, {'name': 'skill', 'status': crafts}] It will be retrieved because all of its requirements match the user's dictionary. It there were a 3rd requirement: [{'name': 'gender', 'status': 'female'}] Then it would not be retrieved. However, if that 3rd requirement's status were male, it would match and be retrieved. Currently, I am iterating through each program and checking if there is a match, but I feel like there must be a better way to execute this: for p in program: for r in p.requirements.all(): if user_dict[r.name] == r.status: print "Match" else: print "No Match" -
Django static image not loading for a CSS div background
I have a Django site, whose home page contains a div that has it's background image defined as: .background-1 { {% load static %} background-image: url("{% static "personal/images/ind.jpeg" %}") ; } Now, as I do ./manage.py runserver and open the localhost, the site runs properly, but the image is not shown in the background. From what I know about Django, url must need a url. Thus the image should be loaded via : {% url 'url-pattern-name' 'input' %}, which would need a few modifications in the views.py and urls.py files. Otherwise, I would need to remove this part from the CSS, and add a src = {% static "pers...%} to the div tag, directly into the html. I just am not sure, if there is no other way to solve this problem. Specifically, with using the static call. -
Error only present when using Django Nose test runner: View must be a callable or a list/tuple in the case of include()
All of my tests run as expected when I use Django's default test runner. When I add TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' to my project's settings, I receive a TypeError that states view must be a callable or a list/tuple in the case of include(). I'm using Django version 2.1.5—and don't really have any idea where to start debugging this error. In this case the only difference between my tests running and throwing an error is the inclusion of the above line into my settings.py file. Has anyone run into this problem before? I'm getting it with all of my views. My main mysite/urls.py paths look like this (as per Django's documentation): urlpatterns = [ path('admin/', admin.site.urls), path('sound/', include('sound.urls')), ] Which, just to see if it'd do anything, I changed to: from sound import urls as sound_urls urlpatterns = [ path('admin/', admin.site.urls), path('soundtests/', sound_urls), ] But this did not change the error at all. This is not a duplicate of any of the other questions with this error. This problem only occurs when I use django_nose as my test runner. I am not referencing my views with strings in any of my urls.py files. -
django-rest-swagger 2.2.0 endpoints with auth classes not visible
I have a bunch of endpoints that have custom and basic auth classes defined, but swagger shows only endpoints that don't have authentication classes and have a permission class = AllowAny. How to make all endpoints be visible at 'docs/' endpoint without any authentications/permissions? djangorestframework==3.9.1 django-rest-swagger==2.2.0 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ) } SWAGGER_SETTINGS = { 'exclude_namespaces': [], # List URL namespaces to ignore 'api_version': '', # Specify your API's version. Might be useful in future 'api_path': '/', # Specify the path to your API not a root level 'enabled_methods': [ # Specify which methods to enable in Swagger UI 'get', 'post', 'put', 'patch', 'delete' ], 'token_type': 'Bearer', 'api_key': {}, # An API key 'is_authenticated': False, # Set to True to enforce user authentication, 'is_superuser': False, # Set to True to enforce admin only access } -
Pip freeze --local
I just started learning Django a couple of hours ago. Frankly saying I am lost. And probably this question may look kinda funny, but I hope you will answer before down-voting ;) Okay here is the question: I am following a video tutorial and that guy did a weird thing like this: $ pip freeze --local > requirement.txt $ cat requirement.txt Of course that is not weird for you. Okay, he said that we did this to export all these packages with their versions in another project, but he didn't explain what is pip-freeze? and what is that requirement.txt? are we supposed to export all those packages in a txt file, how can .txt file do that does it grab their name? !important What is the word cat in second line can I put tom instead because my machine can't understand either of those, but in his computer they were working, my machine says: sorry I don't know how to copy from cmd so I put a screenshot. Result : As you can see cat is not recognized. Then I look in virtualenv directory to search for requirement.txt and I find this Yes, requirement.txt is zero bytes, nothing in it. … -
How to Pass option from search into url
Currently i have a search that returns models matching the input. My goal is to add a dropdown to this search and pass that into the url for the use of separate views in one template. So my search form would look like this index.html <form method="GET" action = "{% url 'app:search' %}"> <input name="q" type="text" placeholder="search by Key or Name"/> <select name = "category"> <option value = "1"> Category 1</option> <option value = "2"> Category 2</option> <option value = "all"> All</option> </select> <input type="submit" value="Search"/> </form> I need my urls to look something like this urls.py app_name = 'kpi' urlpatterns = [ path('login/index/', views.IndexView.as_view()), path('login/index/<category option here>/search', views.SearchView.as_view(), name="search"), path('login/index/<category option here>/<slug:key>', views.ModelView.as_view(), name="detail"), ] I am able to grab the key and push that to the url on the search results page no problem like this search.html <ul> {% for x in results %} <li><a href = "{% url 'kpi:detail' x.key %}">{{x.name}}</a></li> {% endfor %} </ul> And able to grab the key by using a get function like so in my views def get(self, request, *args, **kwargs): self.q = self.kwargs['key'] return super().get(request, *args, **kwargs) But since category isnt part of this model's schema i cannot use this same … -
Is there something like Django Modelform for go
I'm working on a go project using the Gin Web Framework. I am serving a few simple CRUD type models. I've used gorm to create these models. I am wondering if there is something like the ModelForm from Django available for go. I have started to write my own with struct tags, but would prefer to use an existing project or system if it exists. -
How to set cookie value to HttpResponse and then return a redirect in Django?
I am trying to convert a node.js express.js app to Django app. Here are two url views in nodejs expressjs. app.get('/app', (req, res) => { if (store) { const state = nonce(); #Creating a random string res.cookie('state', state); #Setting a cookie to response res.redirect('/app/success'); #Redirect to below view } else { return res.status(400).send('Request 400'); } }); And this is another one app.get('/app/success', (req, res) => { const { state } = req.query; const stateCookie = cookie.parse(req.headers.cookie).state; if (state !== stateCookie) { return res.status(403).send('Request origin cannot be verified'); } } else { res.status(400).send('Required parameters missing'); } }); And in doing so I wrote this def storeView(request): if(store): state = get_random_string(length=32) #equivalent of noonce() HttpResponse().set_cookie('state', state) #res.cookie('state', state); return redirect('/app/success') #res.redirect('/app/success'); else: return HttpResponseBadRequest() But when I try to retrive the cookie, it gives error. def callbackview(request): response = HttpResponse() stateCookie = request.COOKIES['state'] #this gives error if (shop and hmac and code): return HttpResponse("checkpoint 2") else: return HttpResponseBadRequest() else: return response -
Django MySQL error when running tests in a virtualenv
I have a Django app working perfectly on my local Python 3.6 version and want to make sure that it will do so when installed elsewhere. For this reason I created a virtualenv using precisely the same Python version which works fine globally, but without any packages: virtualenv --no-site-packages --python=$(which python3.6) clear_env source clear_env/bin/activate Then I installed the requirements locally: pip install -r requirements.txt When I try to run the server, or even when I used the admin panel and make changes to the DB, everything works. However, when I run the tests: python manage.py test --nomigrations I get the following error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) NOT NULL, `user_id` integer NOT NULL, `content_type_id` integer NULL, `objec' at line 1") which tracebacks to: File "/home/niki/basic-django-ecommerce-site/clear_env/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/home/niki/basic-django-ecommerce-site/clear_env/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/home/niki/basic-django-ecommerce-site/clear_env/lib/python3.6/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/home/niki/basic-django-ecommerce-site/clear_env/lib/python3.6/site-packages/MySQLdb/cursors.py", line 312, in _query db.query(q) File "/home/niki/basic-django-ecommerce-site/clear_env/lib/python3.6/site-packages/MySQLdb/connections.py", line 224, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual … -
decrease the number of a item after selling the item django
i have created an inventory management system , i have two model , in one model it has the number of a specific pc model , the second model is a form for customers , im try to decrease the number of that specific pc after selling the specific pc model class Storage(models.Model): model = models.CharField(max_length=50) company_name = models.CharField(max_length=50) number = models.PositiveIntegerField(null=True,blank=True) serial_number = models.PositiveIntegerField(null=True , blank=True) CPU = models.CharField(max_length=50) RAM = models.PositiveIntegerField() Hard = models.CharField(max_length=15) Graphic = models.PositiveIntegerField() PCs_Number = models.PositiveIntegerField() B_Price = models.PositiveIntegerField() S_Price = models.PositiveIntegerField(null=True , blank=True) cost = models.PositiveIntegerField(null=True , blank=True) cost_Bprice = models.PositiveIntegerField() class UserForms(models.Model): customer = models.CharField(max_length=40) model = models.ForeignKey(Storage , on_delete=models.CASCADE) CPU = models.CharField(max_length=50) RAM = models.PositiveIntegerField() Hard = models.CharField(max_length=15) Graphic = models.PositiveIntegerField() price = models.PositiveIntegerField() get_cost = models.PositiveIntegerField() rest_cost = models.PositiveIntegerField() guarantee = models.PositiveIntegerField(default=7) date = models.DateTimeField(default=datetime.now) -
Django rest framework: CreateAPIView, when the data is stored I want to use the primary key
I'm pretty new to django and python and could use some help. Currently an API-call can be made to my app, which stores the data. But I need to do some business logic after the storage. How do I do this. my view: class ProcList(generics.CreateAPIView): queryset = Proc.objects.all() serializer_class = ProcSerializer permission_classes = (IsAdminOrReadOnly,) lookup_url_kwarg = 'proc_id' # primary key my serializers: class BlobSerializer(serializers.ModelSerializer): # Child (Old Avatar) key = serializers.CharField() value = serializers.CharField() class Meta: model = Blob fields = ('pk', 'key', 'value') class ProcSerializer(WritableNestedModelSerializer): # Father (Old profile) blobs = BlobSerializer(many=True) class Meta: model = Proc fields = ( 'pk', .... Hidden/removed for length purpuse 'service', 'country_code', 'blobs' ) my model (only the Proc-one, since the Blob-model is not important) class Proc(models.Model): # Father (Old profile) MY_SERVICES = ( ("em", 'Email'), ("sm", 'SMS'), .... Hidden/removed for length purpuse ) proc_id = models.AutoField(primary_key=True, help_text="Primary key") service = models.CharField(max_length=2, choices=MY_SERVICES, blank=True, default='mc', help_text='What service is desired, MyChoice is default') .... Hidden/removed for length purpuse country_code = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now=True, name='created_at') My desired outcome is that the API-post-call, stores to the Proc and Blob model as they do now. Given what the "service"-variable is, I want to pass on the … -
django database connection ambiguity
I am working on a small project on news classification. I have trained a keras rnn classifier using anaconda and i have a separate web crawler program to extract news articles from the web. I want to store this crawled data in a sqlite database table and use the classifier to classify and display these articles. My question is i that i have made my crawler using anaconda spyder and i connected to sqlite database to store the articles, i am using django to build the website and django uses its own sqlite connection by default, according to my understanding the database my crawler connects to and the one django uses are different even though both are sqlite databases. How do i make django and my crawler to access the same database table? -
How to upload hundred of documents to a Django Web App?
I developed a Django application and i have to process 500 documents (I have to upload them and to process them one by one using NLP). The problem is that when i try to upload all the 500 documents my app takes so much time, around 2 hours. I would like to know what is the best way to upload these documents using the Django Framework warning the user about the progress? Thank you in advance -
Error installing pygame python setup.py egg_info
It seems the problem lies within the setup paths? Can anyone tell me how to even understand my errors? It won't let me install pygame. Here is the terminal window output once I enter >python -m pip install --user pygame Collecting pygame Using cached https://files.pythonhosted.org/packages/b2/6b/c510f0853765eb2219ca5aa3d416d65bb0dea7cd9bb2984aea0a0e04c24d/pygame-1.9.4.tar.gz Complete output from command python setup.py egg_info: WARNING, No "Setup" File Exists, Running "config.py" Using WINDOWS configuration... Path for SDL not found. Too bad that is a requirement! Hand-fix the "Setup" Path for FONT not found. Path for IMAGE not found. Path for MIXER not found. Path for PNG not found. Path for JPEG not found. Path for PORTMIDI not found. Path for COPYLIB_tiff not found. Path for COPYLIB_z not found. Path for COPYLIB_vorbis not found. Path for COPYLIB_ogg not found. If you get compiler errors during install, doublecheck the compiler flags in the "Setup" file. Continuing With "setup.py" Error with the "Setup" file, perhaps make a clean copy from "Setup.in". --- For help with compilation see: https://www.pygame.org/wiki/CompileWindows To contribute to pygame development see: https://www.pygame.org/contribute.html --- C:\Users\Joshua\AppData\Local\Temp\pip-install-b12x3pbp\pygame\setup.py:321: SyntaxWarning: invalid escape sequence \d return ', '.join(s for s in findall('\d+', ver)[0:3]) Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Joshua\AppData\Local\Temp\pip-install-b12x3pbp\pygame\setup.py", line 203, …