Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CairoSVG - import error happening only on production server
Python version: 3.6 Using Pipenv/Pipfile/Pipfile.lock to manage venvs/dependencies Development environment: Windows Subsystem for Linux (Ubuntu 18.04) Production environment: Ubuntu 18.04 Also using Django: 3.1.4 This project had been working fine on both dev and prod, however, after adding CairoSVG to the venv, I'm now getting an import error only on prod. I've used Pipenv/Pipfile/Pipfile.lock to create the venv on both machines and have verified that both environments are exactly the same. Everything works fine in development after I activate the venv, including this Django-related command: python3 manage.py shell. However, when I activate the venv on production and run python3 manage.py shell, I get the following import error related to the newest dependency, CairoSVG (see the reference to line 6 of models.py below - this is the only cairosvg-related import): Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/virtualenvs/project_name-g-miTQT4/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/opt/virtualenvs/project_name-g-miTQT4/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/opt/virtualenvs/project_name-g-miTQT4/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/virtualenvs/project_name-g-miTQT4/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/opt/virtualenvs/project_name-g-miTQT4/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, … -
Django - how to retain add order when querying m2m field?
I have a CustomUser model, and a models which refer to it through a m2m relationship: class CustomUser(AbstractUser): ... class Game(models.Model): players = models.ManyToManyField( CustomUser, related_name='games',) When I am getting the list of players, I was expecting to receive the list of players by "adding" order, however, the players always show-up ordered by 'id' of the CustomUser table ...even if CustomUser has no ordering at the model level and I didn't saw anywhere in the Django code that there was any kind of ordering in AbstractUser user1=CustomUser.objects.get(id=1) user2=CustomUser.objects.get(id=2) user3=CustomUser.objects.get(id=3) game=Game.objects.create() game.players.add(user3) game.players.add(user1) game.players.add(user2) game.players.all() gives always user1, user2, user3 How do I do to obtain the list of m2m records in the "adding" order(user3, user1,user2) ? I was thinking to ask to order the queryset by 'id' in the through table, but I wasn't able to figure out how to do that. Can somebody show me how I could do that ? ... or propose me a working solution ? Thanks in advance -
update_or_create in my django rest framework api work wrong
My problem in GIF Instead of updating the user's rating DRF creating new. Maybe i made a mistake in serializer? I wrote documentation but i dont kwon where i wrong. My code: views.py: class CreateReviewView(APIView): def post(self, request): review = CreateReviewSerializer(data= request.data) if review.is_valid(): review.save() return Response(status=201) class CreateRatingView(APIView): def get_user(self, request): user= request.user if user =="AnonymousUser": return "noname in CreateRaringView" return user def post(self, request): serializer = CreateRatingSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save(user=self.get_user(request)) return Response(status=201) else: return Response(status=400) serializers.py: class Meta: model = Rating fields = ('star','movie') def new(self,validated_data): rating = Rating.objects.update_or_create( user= validated_data.get('user',None), movie= validated_data.get('movie',None), defaults={'start': validated_data.get("star")} ) return rating models.py: class Rating(models.Model): """Рейтинг""" user = models.ForeignKey(User,on_delete=models.CASCADE,verbose_name="Пользователь",related_name='user') star = models.ForeignKey(RatingStar, on_delete=models.CASCADE, verbose_name="Звезда",related_name="star") movie = models.ForeignKey(Movie, on_delete=models.CASCADE, verbose_name="Фильм",related_name="movie") def __str__(self): return f"{self.star} - {self.movie}" class Meta: #unique_together = ['user','movie','star'] verbose_name = "Рейтинг" verbose_name_plural = "Рейтинги" -
How do I Retrieve an Object Instance with Django RetrieveModelMixin
I would like to retrieve and objects instance with this call: http://localhost:8000/api/get-factor/?code=ABC I have the following: models.py from django.db import models class Factor(models.Model): code = models.CharField(max_length=50, unique=True) value = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.code serializers.py from rest_framework import serializers from .models import Factor class GetFactorSerializer(serializers.ModelSerializer): class Meta: model = Factor fields = ('value',) lookup_field = 'code' urls.py in factors app from django.urls import path, include from factors import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('get-factor', views.RetrieveFactor) urlpatterns = [ path('', include(router.urls)), ] urls.py in project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('factors.urls')), ] views.py from .models import Factor #api from .serializers import GetFactorSerializer from rest_framework import mixins from rest_framework import generics from rest_framework.viewsets import GenericViewSet class RetrieveFactor(mixins.RetrieveModelMixin, GenericViewSet): queryset = Factor.objects.all() serializer_class = GetFactorSerializer lookup_field = 'code' using postman with this call: http://localhost:8000/api/get-factor/?code=ABC results in a Page not found (404) the routes it shows are: api/ ^get-factor/(?P<code>[^/.]+)/$ [name='factor-detail'] api/ ^get-factor/(?P<code>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='factor-detail'] Any suggestions would be appreciated. -
How do I keep track of the two users who will use the website?
I’m storing user profiles in the db which are linked to the individual liked songs of the user. So when a user logs in, the user’s data is stored in the DB. Then I can log the user out with the signoutroute, then another user can log in, then their data is also stored in the dB. Then can use a different route to perform the comparison and give a response. But the problem occurs when another user also uses the app, and another user also does. Let's we have 4 user profiles existing in the db now, how do I make sure I’m getting the last two users to perform the comparison. Example code below works with two profiles i have stored so I know their individual id views.py def liked(request): try: sp = Spotify(auth_manager=oauth) liked = sp.current_user_saved_tracks(limit=30)['items'] spotify_user = sp.current_user() user__ , created = User.objects.get_or_create(username=spotify_user['uri'], first_name=spotify_user["display_name"]) userprofile = UserProfile.objects.get_or_create(user=user__)[0] a = [] for idx, item in enumerate(liked): track = item['track']["name"] artist= item["track"]["artists"][0]["name"] album_ = item["track"]["album"]["name"] tracks = item['track'] val = tracks['name'] + " - " + tracks['artists'][0]['name'] a.append(val) album = Album.objects.get_or_create( Album_name= album_ )[0].save() song, created = Song.objects.get_or_create(track_name = track, artiste_name = artist, album = album) songs_available = … -
Abstract User and Basic Auth with Django Rest Framework (DRF)
I'm currently experiencing some trouble concerning Basic Auth in the DRF. I am testing this with postman using my credentials. These requests are sent to the development server and the request.META["HTTP_AUTHORIZATION"] contains the correct credentials. However, request.user and request.auth are both set to None, which bothers me since it should have at least the User with those credentials (right?). I fear that it has something to do with my custom User model. I've created a new User class which uses the AbstractUser from Django (according to this). Relevant code: class StatusView(APIView): # authentication_classes = [BasicAuthentication] authentication_classes = [] # permission_classes = [IsAuthenticated] permission_classes = [] def get(self, request, uuid, format=None): auth_header = request.META.get('HTTP_AUTHORIZATION', '') auth_type, credentials = auth_header.split(' ') decoded_creds = base64.b64decode(credentials) print(decoded_creds) # <-- this line spits out the credentials that I sent return HttpReponse("") Am I missing something with DRF? It does work with custom user models right? -
Django query ForeignKey object
Can somebody help me to get the ticket object at my queryset shown below?: replies = sorted( chain( SupportTicketReplies.objects.filter(author=request.user, ticket=?!?!) ), key=attrgetter('creation_date'), reverse=True ) Currently I have no idea how to filter out replies that have been attached to a ticket by a ForeignKey. my models.py class SupportTickets(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) ticket_id = models.IntegerField(default=ticket_id_generator, unique=True, blank=False, null=False, editable=False) requester = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) category = models.IntegerField(choices=TICKET_CATEGORY, verbose_name='Ticket Category') subject = models.CharField(max_length=35) problem_description = models.TextField(max_length=2000, blank=False) status = models.IntegerField(choices=STATUS_OF_TICKET, verbose_name='Ticket Status', default=2) creation_date = models.DateTimeField(auto_now_add=True, blank=False) class SupportTicketReplies(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ticket = ForeignKey(SupportTickets, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Author', blank=True) content = models.TextField(verbose_name="Content", max_length=2000) creation_date = models.DateTimeField(auto_now_add=True, blank=False) Thanks in advance -
CreateView display multiple form errors?
I am working with a CBV that uses 2 ModelForm instances. I would like to display the individual form errors. It seems like this is a little challenging when using multiple forms in a class based view. Heres a smaller snippet to show what I am working with... class EmployeeCreate(CreateView): form_class = EmployeeCreateForm form_class_2 = AddressCreateForm def post(self, request, *args, **kwargs): employee_form = self.form_class(request.POST) address_form = self.form_class_2(request.POST) # Make sure both forms are validated if employee_form.is_valid() and address_form.is_valid(): employee = employee_form.save(commit=False) address = address_form.save(commit=False) employee.parent = self.request.user employee.save() address.user = employee address.save() return JsonResponse({'message': 'Employee created successfully.'}, status=200) else: return self.form_invalid(**kwargs) def get_context_data(self, **kwargs): # render both forms to create an Account, and Address context = super(EmployeeCreateView, self).get_context_data() context['employee_form'] = self.form_class context['address_form'] = self.form_class_2 return context def form_invalid(self, **kwargs): return JsonResponse({'success': False}) Now when the form is invalid, the form_invalid method is getting called and returning the JsonResponse message, but I would much rather return the specific form error. I am trying to find a way to display each individual form error for the employee_form and the address_form. Is there a possible way to do this override in the form_invalid method? Thank you in advance! -
Django| generate random url based on URl or PATH from urlconfig
I have a question regarding generating example urls according the Django url and path. For example if I have 2 urls like: path('example/<int:example_id>/', views.some_view, name='example') url(r'^example/(?P<example_id>[0-9]+)/$', views.some_view, name='example') Is it possible to generate somehow by Django built-in means example full-urls for tests like: example/234/ example/93/ example/228/ etc… randomly. For different urls based on concrete name + regex or converter parameters? In other words where in source code Django understands that <int:example_id> is an integer and so on. If I have something like : 1) I expect example/ 2) I expect int - I would be able to use it to generate random example url. Hopefully this is clear... These urls are just an example. Real urls will differ. Thank you. -
Could not load auth.Permission(pk=1): Error to DUMP / LOADDATA Django
Well i tried to dumpdata / loaddata from my site but i keeping get this error bellow. I already look out for some couple solutions, but i keeping get the same error at the end of the day python manage.py dumpdata > dbv5.json or python manage.py dumpdata --exclude=contenttypes --exclude=auth.Permission > dbv5.json then i get the same error: (venv) felipecid@vmgcp2:~/projectBlog$ python manage.py loaddata dbv5.json Traceback (most recent call last): File "/home/felipecid/projectBlog/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'blog_django.auth_user' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) django.db.utils.ProgrammingError: Problem installing fixture '/home/felipecid/projectBlog/initial_data.json': Could not load auth.User(pk=1): (1146, "Table 'blog_django.auth_user' doesn't exist") -
View did not return a HttpResponse object
def login_view(request): if request.method=='POST': user_name=request.POST['username'] _password=request.POST['password'] user=authenticate(request,username=user_name,password=_password) if user is not None: login(request,user) return HttpResponseRedirect(reverse('index')) else: return render(request,'users/login.html',{'message':'Invalid Credentials'}) I am getting the following error message when i go to users/ url The view users.views.login_view didn't return an HttpResponse object. It returned None instead. -
How to solve NoReverseMatch, no arguments not found? (Django)
I am new to Django. I get the following Error: NoReverseMatch: Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['edit/(?P<page>[^/]+)$'] To specify: I am building a wikipedia-like website and now want to allow the feature of editing. Therefore I included path("edit/<str:page>", views.edit, name="edit"), into my urlpatterns at urls.py in my encyclopedia app. For edit, views.py looks like this: def edit(request, page): return render(request, "encyclopedia/edit.html", { "form_newpage": NewPageForm(initial={'content': util.get_entry(page), 'title': page}), "form_searchwiki": SearchWikiForm() }) When I now try to access http://127.0.0.1:8000/edit/CSS - CSS being a valid entry of that encyclopedia - I get the NoReverseMatch Error. In the Traceback the local variable for page is CSS, so I do not understand, why Django does not get CSS as an argument. Traceback get_entry function: def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None -
How to escape a line from within for loop in django template
I have a for loop in django template where I display items from 3 section by using 'if condition' to filter the 3 sections seperately in the loop. But I want to give a heading to each section but if I add a heading also in the 'if condition' it will be repeated with each item being iterated. Is there any way to escape the for loop for a single line within the forloop in django template so that the title for each section won't keep repeating. My django template code: {% for order in orders_today %} {% if order.pickup_time == 'Now' %} <tr> <td colspan="5" align="center"> Orders now </td> </tr> {% endif %} {% if order.pickup_time == 'Now' %} <tr> <td align="center"> {{order.item}} </td> <td align="center"> {{order.quantity}} </td> <td align="center"> {{order.pickup_time}} </td> <td align="center"> </td> </tr> </tbody> {% if order.pickup_time == 'Lunch Break' %} <tr> <td colspan="5" align="center"> Orders at lunch break </td> </tr> {% endif %} {% if order.pickup_time == 'Lunch Break' %} <tr > <td > {{order.item}} </td> <td > {{order.quantity}} </td> <td > {{order.pickup_time}} </td> <td > <button class="btn btn-danger" >Cancel</button> </td> </tr> </tbody> {% endfor %} thanks in advance to the good soul who's gonna … -
Django CMS + Online Shop & Membership [closed]
I have Wordpress with a WooCommerce shop, that sells online memberships. I would like to change the system to Django. I know there are ready-made projects for all parts of the system (CMS, Store, Memberships, .. ), I'm deciding right now if it will be easier to connect and customize these solutions or to start from the ground up. Basically, i need a very simple CMS with a Drag&Drop Editor (i would like to use https://grapesjs.com), Pages that can be locked behind a membership, that is sold in the store. From the store, i actually need only the checkout & payment part, the product catalog is not needed. For a completely custom solution, I'm not sure only about how to receive payments (PayPal, Stripe), but I'm sure i could figure this out. Would you recommend to customize and connect ready-made Django packages (which ones?) or start from scratch? -
hide django-allauth model from admin page
I want hide all django-allauth model from admin page after I see the source code in github I see it use three models SocialAccount, SocialToken and SocialApp. now I use this to hide model from admin page and it works when I try to use it on my own model but when I use it to hide django-allauth model it doesnt work, I think I stuck on the part from x import SocialAccount, SocialToken, SocialApp because the error message is always like this ImportError: cannot import name 'SocialAccount' from 'x' I dont know the x part what to import, where to import -
Two different session value type in Django
I have one dictionary type session and one integer type session in my django request.session. It is giving me an error when it redirects to another view. The error is >>> TypeError at Object of type Product is not JSON serializable. Here is the sample session json: {'com_order_id': 59, 'cart': {'3': {'quantity': 1, 'product': <Product: Christmas With Prestige>, 'total_price': 30000, 'total_weight': Decimal('2.30')}}} If I try to delete the dict session first, it works. Storing both values is giving the error. -
Django AJAX Infinite Scroll Error on page reload
I'm trying to implement infinite scroll with django and jquery(Waypoint). Right now, i have a ListView with a pagination of 5, but when waypoint loads second page, AJAX requests are no longer performed so I added the AJAX function on the onAfterPageLoad which helps bring back AJAX function to the newly loaded page. That's fine, but then it introduces a bug to my code making the page loaded initially (First Page) no longer perform AJAX functions very well. It makes AJAX on the first page run 3 times if I just loaded a third page and makes AJAX on the second page run twice and so on depending on the number of pages loaded already. I don't know if there are any cool ways to achieve this because I tried using just jquery without waypoint, but still get same errors as I get when using just waypoint making it an error. This is kinda tricky so far. class GroupListView(LoginRequiredMixin, ListView): model = Group paginate_by = 5 context_object_name = 'groups' template_name = 'group/group_list.html' ordering = ['-date_created'] <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], offset: 'bottom-in-view', onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function () { $('.loading').hide(); $(document).ready(function(){ function updateText(btn, newCount, … -
TemplateDoesNotExist at
I am new at django. I try to 3.1.4 version django on AWS ec2-instance installed. I get error TemplateDoesNotExist at /. In my settings.py file I have added app to installed apps, and path to templates in dir. This is my base dir. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
How to update data in Django when getting unique field error
first thing first I'm sorry for my bad english. I hope so u can understand me easily. I'm trying to make a blog with django but there's a place I can't solve. I used unique slug field instead of id for url, whenever I want to update the data I get the UNIQUE constraint failed: post_post.url_text error (url_text is slugfield variable name). Here is the my model, and the Form looks like this, At first I followed a way to update the data here: @login_required(login_url='login') def post_update(request, url_text=None): post = get_object_or_404(Post, url_text=url_text) form = PostWrite(request.POST or None, instance=post) if form.is_valid(): post_author = request.user post_title = form.cleaned_data.get('post_title') post_content = form.cleaned_data.get('post_content') post_tags = form.cleaned_data.get('tags') post = Post(post_author=post_author, post_title=post_title, post_content=post_content, tags=post_tags) post.save() context = { 'post': post, 'form': form, } return render(request, 'post/re_write.html', context) and I got the error I mentioned at the beginning of the post. Then I found a solution like this in the forums, if form.is_valid(): form.save() This time it does not give any error but does not update the data. Despite hours of research, for some reason I could not find a tangible solution. I wanted to ask you esteemed coders as a last resort and I look forward … -
object has no attribute 'is_valid'
I am receiving an error, object has no attribute 'is_valid', when trying to insert form data into a form. Below is the structure of my code: model.py enter image description here view.py enter image description here index.html enter image description here -
How to hide a particular attribute of a template from being inherited/included in another template in django?
For example, there are two html templates parent.html which contains button a,button b. and child.html Now I'm extending/including parent in child template and I want only button a to be inherited. How do I achieve this? -
Django Allauth - Override login
I added a field to User model. Now I want to override the django-allauth login view, so I can deny the access to a user with the state "denied". The user after registration active the account but need the admin approval before he is able to login. I have done this without allauth, but now I integrated social account from allauth and I wanted this to be centralized in one app. How can I do this with minimum interference with the native methods from django-allauth? -
from models import Event ModuleNotFoundError: No module named 'models'
from __future__ import unicode_literals from django.contrib import admin from . import models from models import Event I try to build an app from github I get into this problem y", line 6, in from models import Event ModuleNotFoundError: No module named 'models' I am not sure how to fix it.No info onlain this is the repo : https://github.com/alexpnt/django-calendar -
which hashing algorithm should I choose for django? [closed]
I see there are several in the documentation: PBKDF2 is by default and old BCrypt is a popular password storage algorithm Argon2 is the winner of the 2015 Password Hashing Competition Is there an algorithm how to choose one of them? For which situation each is better? Argon2 is the best choice for any situation? I'm not too strong in these area, I need help to choose one. -
python- Why does using a variable not yet defined in "string" manner solves the NameError?
I'm doing some Django project. class Post(models.Model): tag_set = models.ManyToManyField(Tag) class Tag(models.Model): pass The code above invokes 'NameError: name 'Tag' is not defined'. When I change the code by turning the argument into 'Tag', tag_set = models.ManyToManyField('Tag') The problem is solved. I don't know whether it is python's own mechanism or django's. Please help if you know the fundamental principle of the mechanism!