Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Manager object has no attribute 'get_by_natural_key'
I am trying to set up a custom User Model in Django, and believe that the vast majority of my coding is correct, however I am greeted with the following error: 'Manager' object has no attribute 'get_by_natural_key' models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.validators import RegexValidator USERNAME_REGEX = '^[a-zA-z0-9.+-]*$' class MyAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, username, password=None): if not email: raise ValueError("Users must have an email address") if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last name") if not username: raise ValueError("Users must hae an username") user = self.model( username=username, email=email, first_name=first_name, last_name=last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( username, email, first_name, last_name, password ) user.is_admin = True user.is_Staff = False user.is_superuser = True user.save(using=self._db) return user def get_by_natural_key(self, email_): return self.get(code_number=email_) def __str__(self): return self.email def get_short_name(self): # The user is identified by their email address return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" return True def has_module_perms(self, app_label): "Does the user have permissions to view the app 'app_label'?" return True class Account(AbstractBaseUser): objects = MyAccountManager() email = models.EmailField( verbose_name="email address", … -
DJANGO - accesing some user's profile
I'm working on web app and currently I'm developing the profiles part. I've written part to view someones profile and this basically works fine except one thing. I can open someones profile but when I click the tabs which redirects to different part of the profile (these parts are included into block to keep the profile's main information), my code instantly switches to the currently loged user. Is there any way to get the user based on the cookies ? this is the single advert: def view_advert(request, pk, title): advert = Advert.objects.get(pk=pk) return render(request, "advert.html", {'advert':advert}) html <small>from </small><a href="{% url 'profile' nick=advert.user.username %}">{{advert.user}}</a> I open the profile of person who posted the advert (it works) Here is one of the profile and tab: @login_required def profile(request, nick): user = User.objects.get(username=nick) user_profile = Profile.objects.get(user=user) return render(request, "users_templates/profile.html", {"user_profile":user_profile}) def profile_adverts(request, user): user = User.objects.get(username=user) adverts = Advert.objects.filter(user=user) context = { "objects":adverts, "no_data":"No other adverts", "user":user } return render(request, "profile_templates/general_list.html", context) html from profile.html to access tab: <a class="nav-link" href="{% url 'all_adverts' user=user %}" role="tab" aria-selected="false">All adverts</a> Appreciate for help. -
ImproperlyConfigured: Field name first_name is not valid for model CustomUser?
help, Registrations, login, logout is working perfectly but when I try the url http://127.0.0.1:8000/user/ it is showing me this error. Where am I wrong in which step of the program. ImproperlyConfigured: Field name first_name is not valid for model CustomUser? model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractBaseUser): username = models.CharField(_('username'), max_length=100,unique=True) email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(auto_now_add=True) full_name = models.CharField(_("Full Name"), max_length=50, null=True) date_of_birth = models.DateField( auto_now=False, auto_now_add=False, null=True) is_verified = models.BooleanField(_("Verified"), default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.username def has_perm(self,perm,obj=None): return self.is_admin def has_module_perms(self,app_label): return True`from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer serializer.py class RegisterSerializer(RegisterSerializer): full_name = serializers.CharField() date_of_birth = serializers.DateField() is_verified = serializers.BooleanField(read_only=True,default=False) def get_cleaned_data(self): super(RegisterSerializer, self).get_cleaned_data() return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'date_of_birth': self.validated_data.get('date_of_birth', ''), 'full_name': self.validated_data.get('full_name', ''), 'is_verified': self.validated_data.get('is_verified', '') } setting.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep … -
Why can't we use reverse side of ForeignKey relationship in a Django Form?
I'm running into a problem when using a ModelForm and I want to know if I'm crazy or not before I go off making some complicated work-around Use Case: I have the following model definitions: class Setting(models.Model): """Manufacturing settings - can be shared among materials to be manufactured""" ... class Material(models.Model): """Specific record for a material that is manufactured""" ... setting = models.ForeignKey('Setting', on_delete=models.SET_NULL, related_name='materials') class ManufacturingRun(models.Model): """An instance of a manufacturing run""" material = models.ForeignKey('Material', on_delete=models.SET_NULL, related_name='manufacturing_runs') In this application, the data in the Material model is coming from an outside source and we do not provide users the ability to edit these records. However, the setting_id field is not populated as part of the data received from this outside source. Basically I need my users to define Setting instances and be able to assign each record to multiple Material instances. To that end I define a Setting form like so: class SettingForm(forms.ModelForm): class Meta: model = Setting fields = [ ... 'materials' ] Problem: Everything seems fine until I access the View to create a new Setting, thereby triggering the instantiation of a SettingForm object. The server returns django.core.exceptions.FieldError: Unknown field(s) (materials) specified for Setting I've become so … -
Django Form to update another app's database records
I want to be able to update the user app's Profile table favorite_subjects and favorite_courses records from a form inside of my memberships app. This will then allow the {{ user.profile.favorite_subjects }} and {{ user.profile.favorite_courses }} values to change in my template after the form submission. I am not sure how to do that and whether to use an instance variable anywhere in the view. Also not sure how to populate the form with the current values of favorite_courses and favorite_subjects. User app - models.py Profile table: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) favorite_subjects = models.CharField(max_length=20, unique=True) favorite_courses = models.CharField(max_length=20, unique=True) def __str__(self): return self.user.username --------------- Memberships app - memberships/profile.html: {{ user.profile.favorite_subjects }} {{ user.profile.favorite_courses }} <a href="{% url 'memberships:interest_view' %}">Change Interests</a> --------------- Memberships app Urls.py: from .views import ( interest_view ) path('interest_view/', interest_view, name='interest_view'), --------------- Memberships app Forms.py: class InterestsForm(forms.ModelForm): captcha = CaptchaField(widget=CustomCaptchaTextInput) class Meta: model = Profile fields = ('favorite_subjects', 'favorite_courses',) def __init__(self, *args, **kwargs): super(InterestsForm, self).__init__(*args, **kwargs) self.fields['favorite_subjects'].widget.attrs={ 'id': 'favorite_subjects_field', 'class': 'form-control', 'required': 'true', 'autocomplete':'off'} self.fields['favorite_subjects'].widget.attrs['placeholder'] = 'Favorite Subjects' self.fields['favorite_courses'].widget.attrs={ 'id': 'favorite_subjects_field', 'class': 'form-control', 'required': 'true', 'autocomplete':'off'} self.fields['favorite_courses'].widget.attrs['placeholder'] = 'Favorite Courses' self.fields['captcha'].widget.attrs['class'] = 'form-control … -
Single account for users to sign-in on my different websites
I am new to web development. I am developing different websites. I want a system in which users can sign-in on my different websites with a single account because i want to put some functionalities in there. But i have no idea how to achieve this. Please guide me how to do this. -
How to create multiple fields using one attribute in Django-filters
I'm using Django-filters to filter based on categories and price. Price is an attribute of my model, I want to create two filter fields using this same attribute, one for min price and for max price. How can I do that? Can anyone please show me the method to do that? Thanks in advance! My filters.py: class ItemFilter(django_filters.FilterSet): class Meta: model = Item fields = { 'category': ['exact'], 'price': ['lte'] } -
How do you model the following use case in Django?
Together with two friends I have been making a game similar to the drinking game piccolo where you have a list of challenges. Each challenges has variables that need to be filled in (e.g: Player X gives four sips to Player Y). Besides that, a challenge consists of rounds, with each round having an index and a description (e.g Round 0: X and Y drink 4 sips. Round 1: X and Y drink 5 sips now), with X and Y being the same names in both rounds. First we made a small console app that had the challenges hardcoded in them. The list of challenges would look like this: challenge_list = [ Challenge(["p(0)", "rand_phone_number()"],[[0, "{d[0]} moet een nummer bellen. Het volgende scherm bepaalt welk nummer"], [1, "Het nummer is {d[1]}"]]), Challenge(["p(0)", "rand(2,5)", "rand_char('a','z')", "rand(2,5)"], [[0, "{d[0]} noemt {d[1]} dieren die beginnen met de letter {d[2]} of drinkt {d[3]} slokken"]]), Challenge([], [[0, "Alle drankjes schuiven een plek naar links"]]), After requests from other friends we decided that it would be educational to migrate the project to Django, since we did not have much experience in web development and we want to learn something new. We came up with the following model … -
Django Filter on between two different ManytoMany fields
I want to model a Cake with multiple Icings. Each Icings has a flavor. An Icing can belong to multiple Cakes so this needs to be a many-to-many relationship. I achieved the requirement thourgh this model: class Cake(models.Model): layers = models.ManyToManyField(Icing, through='CakeLayer') class Icing(models.Model): flavour = models.CharField(max_length=200) class CakeLayer(models.Model): cake = models.ForeignKey(Cake, on_delete=models.CASCADE) icing = models.ForeignKey(Icing, on_delete=models.CASCADE) order = models.IntegerField() However, I want to query a cake which has a chocolate icing ontop of a vanila icing (i.e chocolate_icing.order > vanila_icing.order) I cannot achieve it through Django's ORM but its rather simple by SQL. SELECT * FROM "cake" INNER JOIN "cakelayer" i1 ON ("cake"."icing" = "reservation_triproute"."id") INNER JOIN "cakelayer" i2 ON ("reservation_triproute"."id" = "reservation_tripstop"."trip_route_id") WHERE (i1.order > i2.order AND i1.icing.flavor="chocolate" AND i2.icing.flavor="vanila" ) I would rather write python code than inject SQL. Any idea how to convert this SQL to Django ORM syntax ? -
How to keep track of users' hobbies/interests in semi-structured way?
Sorry in advance for the long question. I'm not sure the best way to ask it. I am building a social networking platform with the Django/Python web framework. On it, users can create a profile and list their interests or hobbies. I want to match users together based on the number of exact matches and similar matches of their hobbies to create a "compatibility score". For example, there might be a Music category with Jazz, Rock, and Hip Hop genres as well as a Sports category with Football, Basketball, and Soccer, etc. I want there to be a somewhat "standard" list of interests/hobbies so I can analyze them to create a compatibility score. Should I create a standard set of interests and set True/False for every hobby for every user? Or could I only store the hobbies that each user is interested in, but use auto-complete so when a user starts typing their interests, they get prompted to input them in a standard way? Or should I allow them to store their interests/hobbies as free text and use some NLP analyzer to create a compatibility score? If so, what should I use for that? -
How to put "active" class on multiple carousel 's on the same page in Bootstrap
I am trying to add the active class to my first carousel element. But I cannot add it as apparently my selector is wrong. I am using Django templates which have a for loop and I have already added a unique id to each carousel but the script does not work: this is my for loop: {% for post in posts %} {% if post.images %} <div id="carousel-{{ post.title|cut:' ' }}-{{ post.author.username }}" class="carousel slide" data-interval="false" data-ride="carousel"> <ol class="carousel-indicators"> {% for i in post.image_count_as_list %} <li data-target="#carousel-{{ post.title|cut:' ' }}" data-slide-to="{{ forloop.counter0 }}" class="active"></li> {% endfor %} </ol> <div class="carousel-inner"> {% for pic in post.images.all %} <div class="carousel-item"> <img class="d-block img-fluid" src="{{ pic.image.url}}" alt="Content not available"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carousel-{{ post.title|cut:' ' }}-{{ post.author.username }}" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carousel-{{ post.title|cut:' ' }}-{{ post.author.username }}" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> <script type="text/javascript"> $("#carousel-{{ post.title|cut:' ' }}-{{ post.author.username }} .carousel .carousel-item:first").addClass("active"); </script> </div> {% endif %} {% endfor %} and as you can see I am using this script: <script type="text/javascript"> $("#carousel-{{ post.title|cut:' ' }}-{{ post.author.username }} .carousel .carousel-item:first").addClass("active"); </script> But the "active" class I s not being … -
Django-filter How to write filters with DjangoFilterBackend in a POST request?
I have written a custom filter using django-filter package as mentioned in DRF docs here: https://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend Here is my code: class GeoFilter(filters.FilterSet): village_name = filters.CharFilter(field_name='village_name', lookup_expr='icontains', label = 'village_name') country_id = filters.NumberFilter(field_name='block__district__state__country', lookup_expr='exact', label = 'country_id') country_name = filters.CharFilter(field_name='block__district__state__country__country_name', lookup_expr='icontains', label = 'country_name') class Meta: model = Village fields = ['village_name', 'country_id', 'country_name'] class VillagesViewSet(viewsets.ModelViewSet): ''' Villages list with django-filters ''' authentication_classes = [TokenAuthentication] permissions_classes =[IsAuthenticated] serializer_class = VillageSerializer queryset = Village.objects.get_queryset().order_by('id') filter_backends = [filters.DjangoFilterBackend] filterset_class = GeoFilter This is a GET request. I want to write only POST requests with filtering using DjangoFilterBackend. I am trying to find whether it is possible. I am using ORM filter currently but I want to use django-filter as I find it better for filtering. -
Django If statement String Comparison
code.code_type has a string value "mel" and it outputs the same value in the webpage. when i just run {{code.code_type}} But when I compare it in if statement with a string {% if code.code_type == "mel" %} Nothing is happening. {% for code in codes%} {% if code.code_type == "mel" %} <div class="snippet"> <div class="snippet-container"> <div class="snippet-heading"> <a href="#">{{code.code_type}}</a> </div> <div class="snippet-code"> {{code.code_snippet}} </div> <div class="snippet-note"> {{code.code_note}} </div> </div> </div> {% endif %} {%endfor%} -
nginx looking for staticfiles in the wrong place
my Django deployment with ec2, nginx and gunicorn went well beside that my staticfiles are not loading, browser show a 404 error. And this is because nginx looks in a completely different place than statics. At this point I have tried a lot of configurations and nothing does the trick. I am wondering if a pair of fresh eyes can spot a mistake here that I do not. /sites-enabled/django.conf: server { server_name site.net www.site.net; location /static/ { autoindex on; alias /home/ubuntu/saas/static/; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/saas/app.sock; } location ~ \.css { add_header Content-Type text/css; } location ~ \.js { add_header Content-Type application/x-javascript; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/site.net/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/site.net/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.site.net) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = site.net) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name site.net www.site.net; return 404; # managed by Certbot } and my django settings.py look like this and collectstatics works fine. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] STATIC_ROOT = … -
Request from HttpResponseRedirect is called with old URL
I have a template that renders this url: /game/<game_name>/task/<task_id> The idea is render the same template but changing content based on task_id I have this URL path('<str:slug_id>/task/<int:task_id>/', task_page,name='task') that comes from path('game/', include(('game.urls','game'),namespace='game')), And this is the view: def task_page(request,slug_id,task_id): if request.method == 'POST': form = TaskPlayForm(request.POST) if form.is_valid(): task = get_object_or_404(Task,task_id=task_id) puzzle_resultado = task.result puzzle_respuesta = form.cleaned_data['resultTask'] if puzzle_respuesta.upper() == puzzle_resultado.upper(): next_puzzle = task.task_next next_puzzle_id = next_puzzle.task_id return HttpResponsePermanentRedirect(reverse('game:task',args=(slug_id,next_puzzle_id,))) else: return HttpResponseRedirect('/no-resuelto/') return HttpResponse(form.cleaned_data) else: form = TaskPlayForm() template_name = "game_task.html" game = get_object_or_404(Game,slug=slug_id) task = get_object_or_404(Task,task_id=task_id) [..redacted..] context = {"form":form,"game":game,"task":task, "display_items":temp} return render(request,template_name, context) Rendering templates and redirects work fine I'm rendering the same template using the same view from task1 to task2 in this way: /game/example/task/1 --submit form-->/game/example/task/2 But the problem is that rendering /game/example/task/1, then submitting the form redirect to /game/example/task/2 successfully but the task_id request parameter is from previous request (1 in this case). I have tested permanent vs temporary redirects but there is no difference and debugging shows previous task_id value My question is, how can be possible that redirecting to /game/example/task/2, the request parameter task_id is 1? -
Modifying django-filter queryset with callable
I'm trying to modify the queryset of one of my ModelChoiceFilters to depend on the user accessing them. My callable function looks like: (filters.py) def is_client(request): if request is None: return Project.objects.none() return Project.objects.all() This function is being called in the filter class looks like: (filters.py) class ReportFilter(django_filters.FilterSet): project = django_filters.ModelChoiceFilter(field_name='project_name', label='Project', queryset=is_client) class Meta: model = Report fields = ['project'] When coded like this, it always triggers the first condition in is_client. When I try and play around with it and do things with request.user..., I get the error: 'NoneType' object has no attribute 'user'. I have made it so that the queryset which the filter is instantiated with in the view limits what certain users can access, however they can still see the options which are not available to them in the filter (even if when they select it nothing would be returned): (views.py) @login_required def home(request): if is_employee(request.user): reports = ConcreteReport.objects.all() else: client = request.user.id reports = ConcreteReport.objects.filter(project_name__company__user__id=client) myFilter = ReportFilter(request.GET, queryset=reports) context = {'reports':reports, 'myFilter':myFilter} return render(request, 'dashboard/home.html', context) I can't figure out why the request is a NoneType, as I use it in the view for other things and it has attributes. Any help is … -
Store a non-JSON serializable object in session
I have object of type OAuth1 oauth = OAuth1(CLIENT_ID, client_secret=CLIENT_SECRET, resource_owner_key=request.session.get('resource_owner_key'), resource_owner_secret=request.session.get('resource_owner_secret')) I do not want to have to create this object every-time an API is hit so I would rather store it in a session. It isn't JSONSerializable though What are my alternatives? I realize it isn't allowed to store objects in sessions since Django 1.6 . Creating the same object repeatedly does not look like a good option to me. For reference, The decorator that looks like this : def oauth_verify(view_func): def _wrapped_view_func(request, *args, **kwargs): if not request.session.get('oauth'): if (request.session.get('resource_owner_key') and request.session.get('resource_owner_secret')): oauth = OAuth1(CLIENT_ID, client_secret=CLIENT_SECRET, resource_owner_key=request.session.get('resource_owner_key'), resource_owner_secret=request.session.get('resource_owner_secret')) request.session['oauth'] = oauth else: return JSONResponse(result=json.dumps({ "Exception": "NotAuthorized", "Error" : "You are not authorized, please log on" }), message='failure') return view_func(request, *args, **kwargs) return _wrapped_view_func -
Django Whitenoise not serving static files sometimes in ECS with debug False
My static files are not being served nicely in production with Whitenoise and Debug=False . Sometimes it serves, sometimes it doesn't find the static. I have the following settings: # Static / Media MEDIA_URL = os.environ.get('MEDIA_URL', '/media/') MEDIA_ROOT = os.path.join(BASE_DIR, '.media') STATIC_URL = os.environ.get('STATIC_URL', '/staticfiles/') STATIC_ROOT = os.path.join(BASE_DIR, '.static') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/static'), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... On deploying to AWS ECS, I'm collecting static normally on docker. If I run python manage.py collectstatic locally I can find the files on my STATIC_ROOT. On production if I access via browser sometimes it returns the static correct, sometimes it gives a 404 error. What it could be? Any help please. -
Django OperationalError 'no such column:' sqlite
For my basic, rudimentary Django CMS, in my effort to add a toggle feature to publish / unpublish a blog post (I’ve called my app ‘essays’ and the class object inside my models is is_published), I’ve encountered an OperationalError when trying to use the Admin Dashboard to add essay content. I’m expecting to be able to switch a tick box to publish/unpublish but now I can’t even access the Dashboard. Here is part of the traceback from my Django server: File "/home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: essays_essayarticle.is_published The debug traceback reinforces the OperationalError above: OperationalError at /admin/essays/essayarticle/ no such column: essays_essayarticle.is_published Request Method: GET Request URL: http://<DN>.ngrok.io/admin/essays/essayarticle/ Django Version:2.2.11 Exception Type: OperationalError Exception Value: no such column: essays_essayarticle.is_published Exception Location: /home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/bin/python `Fri, 1 May 2020 19:37:31 +0000 Exception Value indicates ‘no such column’ which is a reference to my db. I’m running SQlite3 for test purposes. Prior to this OperationalError, I was troubleshooting issues with a DummyNode and "isinstance django.db.migrations.exceptions.NodeNotFoundError: Migration". The previous solution I arrived at was to delete my migrations in two of my … -
Optimize ORM queries in Flask using Flask-SQLAlchemy
I have written the same project using Django and Flask. The entire code is available on my Github account. The website is a small question-answer based quiz website (in CTF format with very easy questions). Here are the links: Django Project Flask Project My question is regarding optimizing ORM queries in SQLAlchemy or Flask-SQLAlchemy. I'll try to write the schema of the tables as well as I can for better understanding. Teams (id, team_name, email, phone, password) Questions (id, name, body, hint, answer, points, visible) Submissions (id, team(fk), question(fk), timestamp) In case any of you want to see the actual code, here they are: For Django - Question & Submission, Team For Flask - Question, Team, Submission For two of the routes, /submissions and /leaderboard, I had to write certain queries using the ORM. This is how the pages look like: For Django, the queries look pretty good (or at least I think so :P ) def submissions(request): all_submissions = Question.objects \ .values('id', 'name') \ .order_by('id') \ .annotate(submissions=Count('submission')) print(all_submissions.query) return render(request, 'questions/submissions.html', { 'submissions': all_submissions }) def leaderboard(request): team_scores = Team.objects \ .values('team_name') \ .order_by('team_name') \ .annotate(score=Coalesce(Sum('submission__question__points'), 0)) \ .order_by('-score') print(team_scores.query) return render(request, 'questions/leaderboard.html', { 'team_scores': team_scores, }) And the … -
Django queryset ordering by fields
i'm using django 2 and in my list view i want to oder the queryset by likecount and datetime field. The main goal is to odering the post with mostlikes for today. Like, i want to show the most liked posts for today. It's like todays top 10 post(mostliked). i have tried many ways but can't figure it out. I hope you guys can help me. My models.py: class post(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100) image = models.ImageField(upload_to='post_pics', null=True, blank=True) content = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) restrict_comments = models.BooleanField(default=False) watchlist = models.ManyToManyField(User, related_name='watchlist', blank=True) def __str__(self): return self.content class Meta: ordering = ['-date_posted', 'title'] def get_absolute_url(self): return reverse ('blog-home') def total_likes(self): return self.likes.count() My views.py: @login_required def most_likes(request): posts = post.objects.annotate(like_count=Count('likes')).order_by('-like_count', '-date_posted') context = {'posts': posts} return render(request, 'blog/most_likes.html', context) -
What environment variables do I need to include in a bash script in order to run a Django migration?
I'm running Python 3.7, Django 2, on Mac OS X. When I run the following commands from the command line, they work seamlessly ... localhost:web davea$ source ./venv/bin/activate (venv) localhost:web davea$ python manage.py migrate maps System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: maps Running migrations: No migrations to apply. However, when I create a bash script containing the commands !#/bin/bash source ./venv/bin/activate python manage.py migrate maps The script dies localhost:web davea$ sh test.sh test.sh: line 1: !#/bin/bash: No such file or directory Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File … -
Python, Django3 error 'QuerySet' object has no attribute 'patterns'
I am very new in Python and Django. I have problem with request in my app. I want to get the value for pattern in part model (reletionship M2M) And i have django error: 'QuerySet' object has no attribute 'patterns' What is the error and how to fix it? Thanks for help Models.py from django.db import models class Pattern(models.Model): patternName = models.CharField(max_length=64) def __str__(self): return self.patternName class Part(models.Model): unitsList = ( ('szt', "szt"), ('m', "m"), ('komp', "komp") ) partName = models.CharField(unique=False, max_length=128) code = models.CharField(unique=True, max_length=15) units = models.CharField(max_length=10, choices=unitsList, default='szt') description = models.TextField() pattern = models.ManyToManyField(Pattern, related_name='patterns) def __str__(self): return self.partName views.py from django.shortcuts import render, from .models import Part, Pattern def partList(request): allParts = Part.objects.all() allPatterns = allParts.patterns.objects.all() return render(request, 'partList.html', {'parts': allParts, 'patterns': allPatterns}) partList.html {% for part in parts %} <tr> <td>{{part.partName}}</td> <td>{{part.code}}</td> <td>{{part.units}}</td> <td>{{part.description}}</td> <td>{{part.producer}}</td> <td>{{part.pattern}} </td> <td> <!-- <a href="../editPart/{{part.id}}">EDYTUJ</a> <a href="../deletePart/{{part.id}}">USUN</a> --> <a href="{% url 'editPart' part.id %}">EDYTUJ</a> <a href="{% url 'deletePart' part.id %}">USUN</a> </td> </tr> {% endfor %} -
How to keep the page paginated using django-filters when no filter is applied?
I'm using django-filters to filter categories and price. My problem is that, when I'm filtering results, it's paginated, but when there are no filters applied, there is no pagination. How can I add pagination when there are no filters applied? Thanks in advance! My filters.py: import django_filters from .models import Item class ItemFilter(django_filters.FilterSet): class Meta: model = Item fields = { 'category': ['exact'], 'price': ['lte'] } My views.py: class homeview(ListView): model = Item template_name = 'products/home.html' paginate_by = 8 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = ItemFilter(self.request.GET, queryset=self.get_queryset()) return context My home.html: <div class="card"> <div class="card-body"> <div class="container"> <form method="GET"> {{ filter.form|crispy }} <button type="submit" class="btn btn-primary mt-4">Filter</button> </form> </div> </div> </div> <h1 class="mb-4">List Of Items</h1> <div class="row"> {% for item in filter.qs %} .... {% endfor %} -
Django Testing Package Installed by PIP Locally
When developing in Django, we can use the following command (or its variations) to run tests on all the apps written by us: python manage.py test. This will make Django look for test directories, as well as files with names along the lines of test_*. What I am wondering about is whether there is a way to include into the testing a package that was installed via pip install -e /path/to/package/here. I am trying to do this because I want to change some code in this package to make it compatible with a latter Django version. The package does have unit-tests in the test directory. However, it seems that it needs a virtual environment with Django to run those tests. Upon creating one, it is discovered that one needs to set up a project with settings to get it to work. Hence, my thought was: if we already have a project that is using this package, can we not run its tests from the project itself? If there is a better way of doing it, I am happy to hear it.