Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django slug works for one word but when it's more than one words it collapses
with a small word like "cool" it works but if it's like "not cool" then it doesn't work because slug makes it not-cool. path('<slug>/', views.series_pg, name='series_detail'), class Series(models.Model): slug = models.SlugField(unique=True) def get_absolute_url(self): return "/%s/" %self.slug def series_pg(request, slug): series = Series.objects.get(name=slug) if slug changes the original word then it doesn't work -
How to get out of Apache log file
I am trying to trace some errors and I used an Apache error log command that left me stuck on a search in my console. All it says is log file: I have tried to use a handful of commands to exit but I cannot seem to find out how. What is the command to exit the apache error log files? -
Trouble installing django inside virtualenv
I am new to this environment, and I would like to make sure I have the proper setup. When running 'pip install django' inside my virtualenv, this is what I get: DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. Collecting django Using cached https://files.pythonhosted.org/packages/8e/1f/20bbc601c442d02cc8d9b25a399a18ef573077e3350acdf5da3743ff7da1/Django-1.11.20-py2.py3-none-any.whl Requirement already satisfied: pytz in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from django) (2013.7) Installing collected packages: django ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/Django-1.11.20.dist-info' Consider using the --user option or check the permissions. Furthermore, when I install with --user, I am unable to create a project with 'django-admin' as the command is 'not found'. I would greatly appreciate any nudge towards the right direction, so I can get started with this environment as soon as possible. Cheers! -
Migrations File too Large preventing Migrate
In Django 2.2, I run makemigrations then migrate. I wait approx. 5-7 minutes and then I get "Fatal Python error: Cannot recover from stack overflow." "Current thread 0x0002094 (most recent call first):" yada yada "File "manage.py", line 17 in main "File manage.py line 21 in " End. I check the migrations file and the file is 4000 lines of code large. What do I do in this case? Should I make my own migration files, and if so, how? -
How to keep track of active websocket connections
The django channel docs mention this regarding keeping track of websocket connections They do not allow you to enumerate or list the channels in a group; it’s a pure broadcast system. If you need more precise control or need to know who is connected, you should build your own system or use a suitable third-party one. I was wondering if there already exists a standard way to do that? Is anyone aware of any library or open source project for this? P.S My use-case is chatbot application using django-channelsand I need to initialize a common chatbot object if the number of websocket connections is greater than one and destroy it if there are no websocket connections. -
DJango REST Framework: How to write Create, List, Update and Delete with ModelViewSet
I'm still new to python/django and currently I'm trying to add REST API using django rest framework. This is currently what I have: urls.py actions_url = {'actions': {'get': 'list', 'post': 'create'}} actions_obj = {'actions': {'get': 'retrieve', 'delete': 'destroy', 'put': 'update'}} urlpatterns = [ path('book', BookViewSet.as_view(**actions_url)), path('book/<str:isbn>', BookViewSet.as_view(**actions_obj)) ] models.py (The model doesn't have PK) class Book(models.Model): BNAME = models.CharField( db_column='BNAME', max_length=30, default='') BISBN = models.CharField( db_column='BISBN', max_length=10, default='') views.py class BookSerializer(serializers.ModelSerializer): name = serializers.CharField(source="BNAME") isbn = serializers.CharField(source="BISBN") class Meta: model = models.Book fields = ('name', 'isbn') class BookViewSet(viewsets.ModelViewSet) queryset = Book.objects.all() serializer_class = BookSerializer def list(self, request): return queryset def create(self, request): pass def retrieve(self, request, *args, **kwargs): pass def update(self, request, *args, **kwargs): pass def destroy(self, request, *args, **kwargs): pass So now my questions are: If I'm not including def create(self, request) in the BookViewSet for example, I assume when I make a POST /book it will do nothing? I'm struggling to understand what to put inside create, retrieve, update, destroy. For example if I make a PUT /book/123 with params: { isbn: '123', name: 'test'}, what do I need to do in def update to retrieve those data from request then update data to database? I want to … -
OAuth2 Flow for SSO: How to associate login with Django user?
I have Django (DRF) and React stack with an OAuth2, which has been issued by my place of work with proper credentials and endpoints. Essentially, I want to be able to have users within the company to access this fullstack application via SSO. My OAuth2 flow is as follows: Redirect to the /as/authorization.oauth2 endpoint in the React frontend On success redirect to Callback handler in frontend with code param On componentDidMount take code param and query DRF API endpoint This endpoint will internally query the token exchange endpoint /as/token.oauth2 If successfully exchanged, JWT decode the token in the response to get userinfo It's simple enough to pass codes between frontend and backend. It's simple enough to verify a successful authentication from the user. My question essentially is how do I associate a frontend SSO instance with a user in the Django backend? Furthermore, how can I delete the frontend SSO instance and its related cookies when calling the logout endpoint in the backend, so as to end the session? -
How to use Prefetch related in a manytomany relation using PK selected (DJANGO)
How can I display the Category : many to many relation the movie belongs to in the detail page based on the pk selected on the List Page. I am looking for a way to accomplish this using prefetch_related i possible. Any other way is fine too. models.py class Movie(models.Model): title = models.CharField(max_length=70) description = models.TextField(max_length=500) class Category(models.Model): name = models.CharField(max_length=70) movie = models.ManyToManyField(Movie, related_name='categories') views.py class MovieListView(ListView): model = Movie context_object_name = 'movies' template_name = 'snippets/index.html' def get_queryset(self): return Movie.objects.all() class MovieDetailView(DetailView): model = Movie template_name = 'snippets/detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['movie_name'] = get_object_or_404(Movie, pk=self.kwargs.get('pk')) return context Any help would be much appreciated. -
Get objects by 10km in django, when models saved via googlecords
I have a models "Vendor", that have lat, lon fields as cords, when user saved address, its automat saved in lat long by google geolocation cords api. I need to filter vendors when user filtering nearist objects, to get vendors only in 10 km.. Can someone tell me what how i can make it? -
Why am I getting an internal server error when deploying Django with Heroku (admin page still works)?
I am trying to deploy my Django website with Django with Heroku, and it keeps showing me "Internal Server Error." None of the other answers regarding this same problem here at SO solved my problem, and I noticed that I only have this problem when I set DEBUG to False. My heroku logs commands show me the following error: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for '/images/posting/bike.png' I have setup my settings the following way: ALLOWED_HOSTS = ["stratagembetaapp.herokuapp.com"] STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" django_heroku.settings(locals()) Additionally, gunicorn, django-heroku, and whitenoise are perfectly installed. My requirements.txt and Procfile are also in order. I have also already run the "python manage.py collectstatic" in the Heroku shell, but I still get the same result. -
Django save() runs INSERT instead of UPDATE: Why?
Consider the following Django model: class Outlet(models.Model): a = models.CharField(max_length=253, primary_key=True, db_index=True) def _split(self, idx): if not self.a: return None return self.a.split(".")[idx] @property def b(self): return self._split(0) @property def c(self): return self._split(1) Couple with this class registered in admin: @admin.register(Outlet) class OutletAdmin(admin.ModelAdmin): fields = ("a", "b", "c") readonly_fields = ("b", "c") Start with an empty DB: Add one instance in the admin UI: Fine so far. Now go to modify that instance: Huh? What just happened? Django just performed an INSERT when it should reliably be expected to perform an UPDATE. Directly from How Django knows to UPDATE vs. INSERT: You may have noticed Django database objects use the same save() method for creating and changing objects. Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save(), Django follows this algorithm: If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT. Now, this question will tell me that this is because a is a primary … -
postman env file don't exist in tutorial
I learn Postman from tutorial https://thinkster.io/tutorials/testing-backend-apis-with-postman/managing-environments-in-postman And at step when I should download env file from link, link is don't exist? Can someone help me ? P.S.:Sorry for bad english -
django-elasticsearch-dsl sort results by score
I'm trying to sort the results returned by elastic search to make them more relevant to my users. I have a large database (100M+ items) and I need to search them by name while allowing spelling mistakes (fuzziness of 1). For example, when I search "jump", the results are : - "bump" - "bump 1" - "bump 2" - ... - "jump" - "jump 1" - "jump 2" I'm looking for 2 things : - A way to display the score of every match - A way to order the results by score so then "jump" goes before "bump". documents/product.py from django_elasticsearch_dsl import DocType, Index, fields from elasticsearch_dsl import analyzer from main.models import Product product = Index('products') product.settings( number_of_shards=1, number_of_replicas=0 ) text_analyzer = analyzer( 'text_analyzer', tokenizer='standard', filter=[ 'asciifolding', 'lowercase', 'snowball', 'stop', ] ) @product.doc_type class ProductDocument(DocType): name = fields.TextField(analyzer=text_analyzer) class Meta: model = Product fields = [ 'code', ] queryset_pagination = 5000 def prepare_name(self, instance): if instance.name: return instance.name.replace('-', ' ').replace('_', ' ') else: return None search.py from ..documents import ProductDocument from elasticsearch_dsl import Q def search(searched_text): name_options = { "query": searched_text, "operator": "and", "fuzziness": "1", } brand_options = { "query": searched_text, "operator": "and", "fuzziness": 1, } query = Q("match", … -
Restricting a django page to unverified accounts
I am creating a Django site, and i would like to have some parts of this site restricted to users who did not confirm their email address. Basically, if you try to open X page and your email is not confirmed, you'll get an error. I found a solution, but it's not working. Here is what i did: I have been suggested to add a separate model for this: class account_emailconfirmation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @property def has_verified_email(self): return self.user.emailaddress_set.filter(verified=True,primary=True).exists() And this is what the template looks like: {% extends "main/header.html" %} {% block content %} {% if user.account_emailconfirmation.has_verified_email %} <style> </style> <body> <div> <p>Here goes a bunch of features</p> </div> </body> {% else %} <p> Your email is ot confirmed </p> {% endif %} {% endblock %} The current solution has a problem: for some reason, even if the email is confirmed, i'll still get 'Not confirmed', while it should allow me to see the page if my email is confirmed. Here is what my db looks like: There is a table called account_emailconfirmation, then there is an index, verified, that will give 0 when the account is not verified, 1 when it is verified. Any advice is appreciated! … -
Django model is saving twice
I'm trying to save Authors model, but it keeps saving twice into the database. views.py for book_data in data['items']: volume_info = book_data['volumeInfo'] title = volume_info['title'] genres = volume_info.get('categories') authors = volume_info.get('authors') description = volume_info.get('description') if not Books.objects.filter(title=title).exists(): book = Books.objects.create(title=title, description=description) # Does authors exists in database? existing_authors = Authors.objects.filter(author_name__in=authors) existing_authors_names = {authors.author_name for authors in existing_authors} # Create a list of missing authors missing_authors = [ Authors(author_name=author_name) for author_name in authors if author_name not in existing_authors_names ] # Creating author before adding it to relation if missing_authors: missing_authors = Authors.objects.bulk_create(missing_authors) print(missing_authors) for m in missing_authors: m.save() # Adding to relation book.authors.add(*existing_authors, *missing_authors) I think the problem is in for m in missing_authors right? -
Jenkins rewrites django settings.py during shell execute
I have this script for jenkins shell execute: #!/bin/bash export WORKSPACE=`pwd` if [ ! -f env/bin/activate ]; then # Create virtualenv virtualenv -p python3 env # Activate virtualenv source env/bin/activate # Install Requirements pip install --upgrade pip pip install -r env/requirements.txt else echo "file env/bin/activate found!" fi if [ -f core/config.py ]; then # Activate virtualenv source env/bin/activate # Install Requirements pip install --upgrade pip pip install -r env/requirements.txt # Run makemigrations and migrate python manage.py makemigrations python manage.py migrate python manage.py collectstatic --noinput python manage.py runcrons else echo "file core/config.py not found!" fi I am using it for CI/CD. I have added some app (fcm_django) into settings.py INSTALLED_APPS section. However, after I push changes to gitlab, and jenkins builds it, settings.py is rewrited, and it comes back to previous state, without fcm_django in INSTALLED_APPS. As a result, I keep getting errors in jenkins: RuntimeError: Model class fcm_django.models.FCMDevice doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I understand that it happens because of fcm_django missing in settings.py, but I can't understand when and why settings.py is rewrited. Please help. Thank you -
e.message_dict keeps throwing exceptions when accessing in test files
I got the following error when I access the variable e.message_dict in testing where e is the ValidationError instance. Creating test database for alias 'default'... System check identified no issues (0 silenced). E. ====================================================================== ERROR: test_invalid_user (userstweetsmanager.tests.test_models.UserTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\sites\tweet_scheduler\userstweetsmanager\tests\test_models.py", line 23, in test_invalid_user password_too_short_user.full_clean() File "C:\Users\love1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 1203, in full_clean raise ValidationError(errors) django.core.exceptions.ValidationError: <unprintable ValidationError object> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\sites\tweet_scheduler\userstweetsmanager\tests\test_models.py", line 26, in test_invalid_user self.assertTrue('password' in e.message_dict) File "C:\Users\love1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\exceptions.py", line 145, in message_dict return dict(self) File "C:\Users\love1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\exceptions.py", line 164, in __iter__ yield field, list(ValidationError(errors)) File "C:\Users\love1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\exceptions.py", line 169, in __iter__ message %= error.params KeyError: 'value' ---------------------------------------------------------------------- Ran 2 tests in 0.005s FAILED (errors=1) Destroying test database for alias 'default'... What I am using: Django: version 2.2.1 Django rest framework: version 3.9.4 I saw the way to access the error message here: https://goodcode.io/articles/django-assert-raises-validationerror/ Here is my models.py import datetime from django.db import models from django import forms from django.core.exceptions import ValidationError from userstweetsmanager.constants import LANGUAGE_CHOICES def password_validator(value): if len(value) < 6: raise ValidationError( str('%(value) is too short (minimum 6 characters)'), code='invalid', params={'password': value} ) class User(models.Model): name = models.TextField(max_length=30, unique=True) password = models.TextField(validators=[password_validator]) … -
ı wanna post two id from .html to views
html file ı wanna take two id to views.py can ı get it ? path('yorum_sil/<int:id>',views.yorum_sil,name="yorum_sil") I want to do this code like the below path('yorum_sil/<int:comment_id> and <int:post_id>',views.yorum_sil,name="yorum_sil") -
How to add data into mysql workbench use”objects.create"
I’m setting up a new website, and want to add data into mysql workbench table, using "objects.create" ,let user text the data ,and create into database. like this models class Record(models.Model): record_id = models.AutoField(primary_key=True) compiler_name = models.CharField(max_length=45) store = models.CharField(max_length=45) goods = models.CharField(max_length=45) account = models.CharField(max_length=45) number = models.CharField(max_length=45) class Meta: managed = False db_table = 'record' views def tech2(request): status_a = True status_check_account = True if request.method == 'POST': check_account = request.POST.get('account', '') check_store = request.POST.get('store', '') check_A = Record.objects.filter(account__exact=check_account) check_S = Record.objects.filter(store__exact=check_store) if check_A: # 如果回傳陣列是空的 status_a = False R1 = request.POST.get('account', '') R2 = request.POST.get('account_check', '') if R1 == R2: # !=改成is not status_check_account = True else: status_check_account = False accounts = request.POST.get('account', '') stores = request.POST.get('store', '') compiler_names = request.POST.get('compiler_name ', '') good = request.POST.get('goods', '') numbers = request.POST.get('number', '') if status_a is True and status_check_account is True: Record.objects.create(goods=good, compiler_name=compiler_names, number=numbers, account=account,, store=stores) return HttpResponseRedirect('/tech/') I want to build a sells website let use type data tech.html <p class="float"> <label for="tech">&nbsp;B</label> <input type="text" name="compiler_name" required autofocus value={{ compiler_name }}> </p> -
How can I save values with user.id to Database - Django
I want to save the values that users enter into the repository. But if the user has already entered a value, I want it to update. It's saving the data right now. But it cannot update. I' am use Django forms.py class Meta(): model = UserProfileInfo fields = ('apikey', 'apivalue', 'apisupplier') views.py def user_set_api(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) current_user = request.user user_form = UserProfileInfoForm(data=request.POST) user_id = current_user.id print('UserId:', user_id) if user_form.is_valid() and user_id: user_form.save(request.user) print('User: ', user, 'Userformid:', UserProfileInfo(['user_id'])) else: print(user_form) else: keysvalue = UserProfileInfoForm() return render(request, 'form.html', {'apisupplier': UserProfileInfo}) models.py user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE) apisupplier = models.CharField(max_length=40, blank=True, default="null") apikey = models.CharField(max_length=40, blank=True, default="null") apivalue = models.CharField(max_length=40, blank=True, default="null") def __str__(self): template = '{0.user} {0.apikey} {0.apivalue} {0.apisupplier}' return template.format(self)``` -
Django print Users list
I want to print list of users, but i'm not sure how to do it mainapp\templates\home.html {% if users %} <ul> {% for user in users %} <li><a href="{% url 'mainapp:lista' user.id %}">{{ user.username}}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} mainapp\views.py from django.contrib.auth.models import User def lista(request): users = User.objects.order_by('-username')[:5] output = ', '.join([q.username for q in users]) return HttpResponse(output) -
Django remove entry from choicefields
I have in my model status with Dropdown: models.py class Item(models.Model): DRAFT = "D" PUBLISHED = "P" CLOSED = "C" STATUS = ( (DRAFT, _("Draft")), (PUBLISHED, _("Published")), (CLOSED, _("Closed")), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name="articleauthor", on_delete=models.SET_NULL) ... status = models.CharField(max_length=1, choices=STATUS, default=DRAFT) ... forms.py class ItemForm(forms.ModelForm): #status = forms.CharField(widget=forms.HiddenInput()) edited = forms.BooleanField(widget=forms.HiddenInput(), required=False, initial=False) content = MarkdownxFormField() class Meta: model = Item fields = ["title", "content", "image", "price", "currency", "status", "edited"] But now I want for by creation new items remove the closed entry. views.py class CreateItemView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): """Basic CreateView implementation to create new articles.""" permission_required = 'is_staff' model = Item message = _("Your article has been created.") form_class = ItemForm template_name = 'item_create.html' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): messages.success(self.request, self.message) return reverse('offers:list') ''' def get_queryset(self): form = self.form = self.form_class(self.request.GET) if self.request.user.is_authenticated(): form.fields['status'].choices.pop("C") form.fields['status'].widget.choices.pop("C") ''' how would you specifically hide the "closed" for the one view? -
DjangoRestFramework, I want the name and not the Id,
I have a relationship in a model, I want you to show me the name you have assigned and not the id of apps.control.models I have: class Movimiento(models.Model): tipo = models.CharField(max_length=1, blank=True, null=True, choices=TIPO)# Compra o Nacimiento descripcion = models.CharField(max_length=20, blank=True, null=True, choices=DESCRIP)# Tipo de animal. Semental, Engorda, Vientre, Reemplazo, Producto fecha = models.DateField(blank=True, null=True) arete = models.CharField(max_length=10, blank=True, null=True) pesonacimiento = models.IntegerField(default=0) raza = models.ForeignKey(Raza, blank=True, null=True, on_delete=models.CASCADE, related_name='movimiento_raza') imagen = models.ImageField(verbose_name="Imagen", blank=True, null=True, upload_to="ovinos") peso = models.IntegerField(default=0) observaciones = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.arete of apps.catalogos.models I have: class Raza(models.Model): codigo = models.CharField(max_length=4,blank=True,null=True) nombre = models.CharField(max_length=100,blank=True,null=True) color = ColorField(default='#FF0000') def __str__(self): return self.nombre my serializer is: class MovimientoSerializer(ModelSerializer): descripcion = serializers.SerializerMethodField() tipo = serializers.SerializerMethodField() class Meta: model = Movimiento fields = '__all__' def get_descripcion(self,obj): dato = obj.get_descripcion_display() return dato def get_tipo(self,obj): dato = obj.get_tipo_display() return dato What can I do to get the name of the race catalog and not the id, can someone help me please? -
Retrive queryset's related data
I have the following model classes: class User(models.Model): ... class Book(models.Model): ... class WishListRelationship(models.Model): user = models.ForeignKey(User, db_index=True, blank=False, null=False, related_name='wishlist', on_delete=CASCADE) book = models.ForeignKey(Book, blank=False, null=False, on_delete=CASCADE) created_at = models.DateTimeField(auto_now_add=True) Then, from user I would like to get the queryset of books with a single call to database. If doing: request.user.wishlist.select_related('book').all() then I have the queryset of WishListRelationship, but I would like to get only books, so I've tried to do the following: Book.objects.annotate(wished_books_ids=request.user.wishlist.all().values_list('book_id', flat=True)).filter(id__in=F('wished_books_ids')) But I didn't achieve what I want, which is getting the list of related books in an INNER JOIN. How could I do that? Thanks in advance -
Django: different behaviour in CreateView and UpdateView with unique constraint
class Badge(Model): # .... class Meta: unique_together = ('identifier', 'restaurant') Using a CreateView, when creating a Badge object whose identifier already exists, I actually get a form error, which is the expected behaviour. But, using an UpdateView, when editing a Badge object whose identifier already exists, I don't get any form error, but a 500 error with duplicate key value violates unique constraint. I can't understand why the behaviour differs. I'd like the form error to be shown in both cases.