Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Conditional Django Query
I am using this query for search. I want to search list according to status, start_date and end_date status can be Active, Inactive, or AllStatus. start_date can be date or None(can be empty) end_date can be date or None(can be empty) status = form.cleaned_data['status'] start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] I made this below query but it is giving me error - Cannot use None as a query value. Can any tell me whats the problem and how should i query using status, start_date and end_date with sometimes value as None Jobs.objects.filter( Q(job_company=self.request.user.userprofile.user_company) | Q(job_created_on__range=[start_date, end_date]) | Q(job_created_on__gt=start_date) | Q(job_created_on__lt=end_date) | Q(job_status=status) ) -
How do I send an email that the password has been changed after password reset is done?
I'm using django 2.1 the default password reset according to documentation https://docs.djangoproject.com/en/2.1/topics/auth/default/ and I need after password reset is completed and the password is updated successfully to send the user an email that he has updated his password successfully How can I achieve that ? -
Bulk update with JSONField in Django
whens = [When(pk=x, then=_json['info'][str(x)]) for x in ids] Clinics.objects.filter(pk__in=ids).update( info_json=Case(*whens, output_field=JSONField()) ) I want to perform bulk update using Case-When statements for JSONField(). When I do this in a stupid cycle with save() on every iteration everithing works fine. But code above writes me:django.db.utils.ProgrammingError: can't adapt type 'dict' saying about second line. I also tried json.loads(), but it didn't work out. What should I do to perform this multiple update? I am using Python 3.6.3 and Django 1.11.16 -
Could not display the updated model using modelForm in django
I am new to django. I am having trouble in displaying some updated data from django model to the html file. I have a delete and add button in the html which will add or remove records to django model. When I click on delete, at the beginning it displays all the records and I can delete the record. Second time when I click, I am getting the previously deleted item also in the list. How can I remove it? I only wanted to display the current items from the model using modelForm. Following is my files: form.py class deleteFileChannelForm(forms.ModelForm): curChannels = getAllChannel('file') j = 0 channelList = [] for item in curChannels: tempTuple = (j, item) channelList.insert(j, tempTuple) j += 1 DeleteChannelName = forms.ChoiceField(widget=forms.Select(attrs={ 'class': 'form-control', }), choices=channelList) class Meta: model = deleteFileChannel fields = ('DeleteFileChannelName',) model.py class deleteFileChannel(models.Model): owaDeleteFileChannelName = models.CharField(max_length=25) def __str__(self): return self.owaDeleteFileChannelName view.py if request.method == "POST": deleteForm = deleteFileChannelForm(request.POST) if deleteForm.is_valid(): data = request.POST.copy() deleteChannelid = int(data.get('DeleteFileChannelName')) deleteChannelName = channelList[deleteChannelid][1] FileChannel.objects.get(FileChannelName=deleteChannelName).delete() return HttpResponseRedirect(reverse('fileChannel', )) else: print("Invalid form") else: formEditChannel = deleteFileChannelForm() return render(request, 'Channels/fileChannel.html',{'formAdd':formAddChannel,'formDelete': formEditChannel, 'channels':allFileChannel}) html file <div class="modal-body"> <form method="post" > {% csrf_token %} <div class="form-group"> <h5>Select channel to delete.</h5> {{formDelete.DeleteFileChannelName}} </div> … -
Django admin restrict access to list view
Here is a model: class Person(models.Model): name= models.CharField(max_length=100, blank=True) identity_number= models.IntegerField(unique=True) name field should be public, identity_number, however, should be confidential. I would like to show name in admin list view and both fields in change form view. I would like to create one group of users, who can access only list view and another group of users, who can access both views. This means that the first group of users should not see links to change form and if they try to access the change form page directly, 403 (or something like that) should be returned. How to achieve this? -
How to send null for Integerfield from form in DRF
I have a simple model: class TestRentalObject(models.Model): some_field = models.TextField() build_year = models.PositiveSmallIntegerField( blank=True, null=True, validators=[MinValueValidator(1300), MaxValueValidator(2100)], ) with ModelSerializer: class TestRentObjectSerializer(serializers.ModelSerializer): class Meta: model = TestRentalObject fields = ( "some_field", "build_year" ) And here is input field from form: <input type="number" class="input-group__input input-group__input_no-require is-invalid" id="field-rent.build_year" placeholder="" name="rent.build_year"> When I keep this field empty, serializer sees it as invalid. In [8]: data = {'some_field': 'some_text', 'build_year': ''} In [9]: rs = TestRentObjectSerializer(data=data) In [10]: rs.is_valid() Out[10]: False In [11]: rs.errors Out[11]: {'build_year': [ErrorDetail(string='A valid integer is required.', code='invalid')]} I believe the problem is that I get build_year as an empty string and not None. But how to do it correctly? -
Django MIGRATION_MODULES in cookiecutter-django
I have been playing a bit with cookiecutter-django and I'm confused about something: They set MIGARATION_MODULES in settings as follows: MIGRATION_MODULES = { 'sites': 'my_awesome_project.contrib.sites.migrations' } and that module contains 3 migrations: 0001_initial.py 0002_alter_domain_unique.py 0003_set_site_domain_and_name.py Those first two are copies of the original Django Sites package, and the third one updates the db with the domain name of the project (as described here). This all makes sense. But what happens if The-Powers-That-Be make another migration in Django Sites? Presumably it would be dependant on migration 0002 as well, leading to a conflict. Would it even get read, given that the MIGRATION_MODULE for 'sites' no longer checks that original module? Just curious. -
Why didn't save Image from SignUpForm to Profile? Django 2.1.5
Faced the following problem. I create form for registration SignUpForm and Profile model. After rigistration image not save in db "Profiles". But if to upload image from admin-panel, it is save. Maybe, error in views.py? How fix it? settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') MEDIA_URL = '/media/' TEMPLATES = [ ... 'context_processors': [ ... 'django.template.context_processors.media' ]}}] urls.py ... + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Profile(models.Model): ... avatar = models.ImageField(upload_to='upload_location', verbose_name="Аватар", default='') ... forms.py class SignupForm(UserCreationForm): ... avatar = forms.ImageField(label='Аватар', required=False) ... views.py def signup(request): if request.method == 'POST': form = SignupForm(request.POST, request.FILES) if form.is_valid(): ... avatar = form.cleaned_data.get('avatar') ... user = form.save(commit=False) user.is_active = False user.save() profile = user.profile ... profile.avatar = avatar profile.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return … -
Django migrate two databases, but one database in mysql was deleted?
There are two database setted in my Django project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'default_db', ... }, }, 'crm': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'crm_db', ... } } And I want to migrate my app ad_management's models into default_db: app structure: ├── ad_management ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tasks.py ├── tests.py ├── urls.py ├── utils models: from django.db import models class Name(models.Model): name = models.CharField(max_length=32) class Meta: managed = True Then I just run python manage.py makemigrations ad_management and python manage.py migrate ad_management, but the db crm_db was deleted as the default db django operating was my default_db. can anyone help me out of this confusion, thanks. -
what happens when we use on_delete=models.CASCADE in django
what happens when we use "on_delete=models.CASCADE" in django models class HospitalStay(models.Model): patient = models.ForeignKey(User, on_delete = models.CASCADE) -
Make deleting by url not possible. Only by direct button click
I have a model form editing template with Save and Delete buttons. I check in the view that the user who tries to delete a post is the owner of it. I use a pop up onlick confirmation. But if I just go to the url (.../post_delete/pk) it deletes the post right away. How do I make sure the deletion is only possible with a button click on the edit template? -
Error in superuser creation NOT NULL constraint failed
I have created a custom user model Student to modify the default signup page provided by Django. from django.db import models from django.contrib.auth.models import AbstractUser class Student(AbstractUser): email = models.EmailField(unique=True) roll = models.CharField(max_length=200, blank=False) contact_no = models.DecimalField( max_digits=10, decimal_places=0, blank=False) I then migrated the database by running: python manage.py makemigrations students python manage.py migrate Now when I try to create a superuser using the command python manage.py createsuperuser, it shows the following error: Traceback (most recent call last): File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 296, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: students_student.contact_no The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 184, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/contrib/auth/models.py", line 161, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/contrib/auth/models.py", line 144, in _create_user user.save(using=self._db) File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 73, in save super().save(*args, **kwargs) … -
Different map pins using Mapbox-gl-js with Django
I'm trying to create a dynamic map of places for my travel blog with Django to be automatically updated based on new entries in database. So far it's going quite good (link: http://puchalatravel.com/map) What I'm having issues with is creating different colour pins based on status field in the database. I'd like to have 4 colors for 4 different status options. I don't know JavaScript well enough to know how to approach the issue. I've googled and tried JS for() loops but didn't manage to make it work.. Currently my code looks as follows: models.py class PlaceStatus(models.Model): status = models.CharField(max_length=32) class Meta: verbose_name_plural = "Place statuses" def __unicode__(self): return self.status def __str__(self): return self.status class Place(models.Model): name = models.CharField(max_length=32) coord_v = models.FloatField() coord_h = models.FloatField() status = models.ForeignKey(PlaceStatus, on_delete=models.CASCADE) trip = models.ManyToManyField(Trip, blank=True, null=True) images = models.ManyToManyField(Image, blank=True, null=True) def __unicode__(self): return self.name def __str__(self): return self.name views.py def map(request): places = Place.objects.all() return render(request, 'blog/map.html', {'places': places}) map.html {% extends 'blog/base.html' %} {% block header %} <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.js'></script> <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.css' rel='stylesheet'/> {% endblock %} {% block banner %} {% endblock %} {% block two_columns %} <div id='map'></div> <script> mapboxgl.accessToken = 'pk.eyJ1IjoibWljaGFscHVjaGFsYSIsImEiOiJjamxxeWk0ZTYwcWJyM3BwbGVzMWpobjFqIn0.sBxqcK2lDMxn9RvqaBfduw'; var map = new mapboxgl.Map({ container: 'map', style: … -
What is virtual environment in Django ? Is it really necessary for a Django project?
While watching any of the tutorials, there is a discussion about making a virtual environment using the command pip install virtualenv What is the use of this virtual environment in Django app development. Where is the formation of Django virtual environment takes place? What is the significance of this virtual environment? -
Django doesn't return request headers to axios
I'm trying to receive a session cookie with axios from a django rest framework backend. I'm using django sessions described here. When I make a post from the command line with httpie, I see several headers, including Set-Cookie with the session token: http post http://example.com:8000/api/ key1=val1 key2=val2 HTTP/1.1 201 Created Allow: POST, OPTIONS Content-Length: 83 Content-Type: application/json Date: Thu, 17 Jan 2019 08:47:16 GMT Server: WSGIServer/0.2 CPython/3.6.7 Set-Cookie: session=e30:1gk3KW:PVn6Pgj-gZQhQue6plWCAONePR4; Domain=*; expires=Thu, 31 Jan 2019 08:47:16 GMT; HttpOnly; Max- Age=1209600; Path=/; SameSite=Lax Vary: Accept, Cookie, Origin X-Frame-Options: SAMEORIGIN { <response params> } But when I do it from axios, the only response header is Content-Type: application/json. I went for the kitchen sink approach with the CORS settings: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_DOMAIN = '*' CSRF_COOKIE_DOMAIN = '*' CORS_ALLOW_HEADERS = default_headers + ( 'Set-Cookie', ) CORS_EXPOSE_HEADERS = ( 'Set-Cookie', ) but to no avail. The view doesn't do much: def post(self, request): request.session.create() request.session.save() return super().create(request) nor does the axios code: axios.post( URL, { key1: val1, key2: val2, } ) .then(response => {whatever(response)}) I'm trying to figure out how to receive the other headers in axios, or at least the reason they're not being received in the first place. I … -
Pass Post Data To Get() - Django
I haveJobListView in which im list the data as well displaying the form. Now when i am posting that i am directly redirected to same page. But now i want to filter out jobs query. So i need that posted data in get(). I am able to print status which is coming from JobSearchForm in post(). But not able to send that status in get(). The reason i want to do this is that i want to filter out jobs query so that only particular list should be displayed. If you have any better approach then please suggest me. class JobListView(LoginRequiredMixin, generic.TemplateView): template_name = 'admin/jobs/job.html' def get(self, request, *args, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) company_name = self.request.user.userprofile.user_company jobs = Jobs.objects.exclude(job_is_deleted = True).filter(job_company=self.request.user.userprofile.user_company) form = JobSearchForm() return render(request, self.template_name, {'form': form, 'jobs': jobs}) def post(self, request, *args, **kwargs): form = JobSearchForm(request.POST) if form.is_valid(): status = form.cleaned_data['status'] print (status) return HttpResponseRedirect('/useradmin/job/') -
Form Validation When Submitting Two Forms
After Submiting Form Before Submitting Form Form error comming for validations. When i remove form_hour from get and post function then form but when i put form_hour then the error of validations comes. Basically i am updating a form named form and creating form_hour. Views.py class ClockOutAddView(LoginRequiredMixin, generic.View): # model = TimesheetEntry template_name = 'admin/clock/clock_form.html' # form_class = ClockOutForm success_url = '/useradmin/timesheet/' def get(self, request, pk, *args, **kwargs): form = ClockOutForm(instance=TimesheetEntry.objects.get(id=pk)) form_hour = ClockOutHourForm() return render(request, self.template_name, {'form': form, 'form_hour':form_hour}) def post(self, request, pk, *args, **kwargs): form = ClockOutForm(request.POST, instance=TimesheetEntry.objects.get(id=pk)) form_hour = ClockOutHourForm(request.POST) print(form.error_class) print(form_hour.error_class) print('Outside Valid') if form.is_valid(): form.instance.timesheet_is_running =False print('Inside Valid') # form.save() # form.instance.timesheet_hour_created_by = self.request.user # form.instance.timesheet_hour_updated_by = self.request.user return HttpResponseRedirect(self.success_url) return render(request, self.template_name, {'form': form, 'form_hour':form_hour}) Form.py class ClockInForm(forms.ModelForm): class Meta: model = TimesheetEntry fields = ['timesheet_jobs', 'timesheet_clock_in_date', 'timesheet_clock_in_time'] class ClockOutForm(forms.ModelForm): class Meta: model = TimesheetEntry fields = ['timesheet_jobs', 'timesheet_clock_in_date', 'timesheet_clock_in_time', 'timesheet_clock_out_date', 'timesheet_clock_out_time', 'timesheet_note' ] Models.py class TimesheetEntry(models.Model): timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users') timesheet_jobs = models.ForeignKey(Jobs, on_delete=models.CASCADE,related_name='timesheet_jobs') timesheet_clock_in_date = models.DateField() timesheet_clock_in_time = models.TimeField() timesheet_clock_on = models.DateTimeField(auto_now_add=True) timesheet_clock_in_by = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_user_clock_in_by') timesheet_clock_out_date = models.DateField(blank=True, null=True) timesheet_clock_out_time = models.TimeField(blank=True, null=True) timesheet_clock_out_on = models.DateTimeField(auto_now_add=True, blank=True, null=True) timesheet_clock_out_by = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_user_clock_out_by') timesheet_note = models.CharField(max_length=100) timesheet_is_edited = models.BooleanField(default=False) timesheet_is_out_edited = models.BooleanField(default=False) … -
Passing arguments as json object
I am trying to link my django web app to Azure ML API. I do have Django form with all the required inputs for my Azure API. def post(self,request): form = CommentForm(request.POST) url = 'https://ussouthcentral.services.azureml.net/workspaces/7061a4b24ea64942a19f74ed36e4b438/services/ae2c257d6e164dca8d433ad1a1f9feb4/execute?api-version=2.0&format=swagger' api_key = # Replace this with the API key for the web service headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)} if form.is_valid(): age = form.cleaned_data['age'] bmi = form.cleaned_data['bmi'] args = {"age":age,"bmi":bmi} json_data = str.encode(json.dumps(args)) print(type(json_data)) r= urllib.request.Request(url,json_data,headers) try: response = urllib.request.urlopen(r) result = response.read() print(result) except urllib.request.HTTPError as error: print("The request failed with status code: " + str(error.code)) print(json_data) # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure print(error.info()) print(json.loads(error.read())) return render(request,self.template_name) When i try to submit the form i am getting type error - TypeError('POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.',) Getting status code - 400 and below error {'error': {'code': 'BadArgument', 'message': 'Invalid argument provided.', 'details': [{'code': 'RequestBodyInvalid', 'message': 'No request body provided or error in deserializing the request body.'}]}} Arguments are using print(json_data) - b'{"age": 0, "bmi": 22.0}' I need to pass arguments as json. Please help. -
Django is not hashing passwords for new users
I am trying to create a signup page with django. I used a normal html form and linked it to django's views and models. However for some reason it won't hash the passwords in the database, it is just storing them as plain text. Not only is this a security issue but it is also not allowing users to login. html form: <div id="signupboxelementscontainer"> <form action="" method="post"> {% csrf_token%} <div id="namerow" class="row"> <input name="firstname"id="firstname" class="formelements" placeholder="First name" type="text"> <input name="lastname" id="lastname" class="formelements" placeholder="Last name" type="text"> </div> <input name="email" id="email" class="formelements" placeholder="Email address" type="email"> <br> <input name="password" id="password" class="formelements" placeholder="Password" type="password"> <br> <input name="passwordagain" id="passwordagain" class="formelements" placeholder="Password again" type="password"> <br> <div class="row"> <input name="areacode" id="areacode" class="formelements" placeholder="+234" type="text"> <input name="number" id="number" class="formelements" placeholder="Mobile phone number" type="text"> </div> <button id="submitbutton" type="submit"> Submit</button> </div> <p>Already have an account? <a href="{% url 'login'%}">Sign in</a> </p> models: class CustomUser(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) email = models.EmailField(max_length=30) password = models.CharField(max_length=100) areacode = models.CharField(max_length=4) number = models.CharField(max_length=30) views: def signup(request): if request.method == "POST": firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') email = request.POST.get('email') password = request.POST.get('password') passwordagain = request.POST.get('passwordagain') areacode = request.POST.get('areacode') number = request.POST.get('number') userdetails = CustomUser(firstname=firstname,lastname=lastname,email=email,password=password, areacode=areacode, number=number) userdetails.save() return render(request, 'main/accountconfirmationpage.html') else: … -
How to specify dictionary parameter in dJango urls?
I am newbie to dJango and got the following error saying that Reverse for 'plot_graph' with keyword arguments '{'column': '["c4", "c5"]'}' not found. 2 pattern(s) tried: ['index/api/plot_graph/(?P<column>[0-9]+)$', 'index/api/plot_graph/(?P<column>[\\w-]+)/$'] My webpage shows me five distinct checkboxes which are c1,c2,c3,c4,c5 and when I click c4,c5 and then click submit button, I can see the above error. below are my codes. urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^form/$', views.Form), # url(r'^api/plot_graph/', views.plot_graph, name='plot_graph'), url(r'^api/plot_graph/(?P<column>[\w-]+)/$', views.plot_graph, name='plot_graph'), url(r'^api/plot_graph/(?P<column>[0-9]+)$', views.plot_graph, name='plot_graph'), views.py def plot_graph(request,column): print(column) data = Data.objects.all() \ .extra(select={'data': connections[Data.objects.db].ops.date_trunc_sql('data', column)}) \ .values(column) return JsonResponse(list(data),safe=False) def Form(request): if request.method == 'POST': if len(request.FILES) !=0: file = request.FILES['files'] column_name = upload_file_name(file) return render(request,"index/form.html",{"column_name":column_name}) else: columns = request.POST.getlist('columns') column_json = json.dumps(columns) return render(request,"index/form.html",{"column_json":column_json}) else: return render(request,"index/form.html",{}) form.html d3.json("{% url "plot_graph" column=column_json|safe %}", function(error, data) { data.forEach(function(d){ d.c5 = d.c5; }); In my case, how to change the urls so that it works? -
Django and DRF, ip limit for request
I need an advise I have some public endpoint created using DRF. Now I want to limit access to it: for example no more than 5 requests in a day. What library/module should I use? Or is there anything in DRF itself? -
Django model instance getattr in multiple database landscape
I have multiple database landscape with "default": {} in databases. I dont need any default db and made this for consistency as suggested in django docs. I also have some Model1 which has related Model2 by FK. Now i am struggling with strange behaviour: having instance of Model1 in one of the databases, i want to get it related instance from Model2, i use: inst1 = Model1.objects.using("mydb").get(...) # this sets inst1._state.db to "mydb related = getattr(inst1, "related_field") and get ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. So instead of respecting inst1._state.db underlying __get__ just init manager with "default" database which leads to this exception. My ugly workaround trying to make generic function for this is: from django.apps import apps related_model = apps.get_model(inst1._meta.app_label, inst1._meta.model_name) related_object = related_model.objects.using(inst1._state.db).get(...) Maybe i am missing something here? -
I can't add a separate image to each article
I can't add a separate image to each article {% for article in articles %} <li> <a href="{% url 'postDetail' id=article.id %}"><img src="{% static 'article.image.url' %}" alt="img" /> </a> <div class="title"><a href="{% url 'postDetail' id=article.id %}"> <h2>{{article.title | safe}}</h2> </a> </div> </li> {% endfor %} -
django-channels not working/not sendind any messages as web socket
by following one of those tutorials over youtube i have just wrote a websocket server using django-channels here is my code signal.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from asgiref.sync import async_to_sync from channels.layers import get_channel_layer @receiver(post_save, sender=User) def announce_new_user(sender, instance, created, **kwargs): if created: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "gossip", {"type": "user.gossip", "event": "New User", "username": instance.username}) consumers.py from channels.generic.websocket import AsyncJsonWebsocketConsumer class NoseyConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add("gossip", self.channel_name) print(f"Added {self.channel_name} channel to gossip") async def disconnect(self, close_code): await self.channel_layer.group_discard("gossip", self.channel_name) print(f"Removed {self.channel_name} channel to gossip") async def user_gossip(self, event): await self.send_json(event) print(f"Got message {event} at {self.channel_name}") apps.py from django.apps import AppConfig class NotifierConfig(AppConfig): name = 'notifier' def ready(self): from .import signals init.py default_app_config = 'notifier.apps.NotifierConfig' routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from notifier.consumers import NoseyConsumer application = ProtocolTypeRouter({ "websocket": URLRouter([ path("notifications/", NoseyConsumer), ]) }) and in channels_layers in settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost",16379)], }, }, } i dont know what the issue is when ever i create a new user using admin i cant see any kind of data that is being transmitted from django websockets over the console … -
Django: Run a script right after runserver
Context: I have a table on the database that uses values from an external database. This external database updates its values periodically. Problem: In order to update my database everytime i start the server, I want to run a script right after the runserver. Potential Solution: I have seen that it is possible to run a script from a certain app, which is something I'm interested in. This is achievable by using the django-extensions: https://django-extensions.readthedocs.io/en/latest/runscript.html However, this script only runs with the following command: python manage.py runscript your_script Is there any other way to run a script from an app and execute it right after the runserver command? I am open to suggestions! Thanks in advance