Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to set up Django, but receiving error in cmd
I'm in the process of learning about django and the different possibilities that it brings, however I am unable to go through the first few steps that I found in pretty much every tutorial. I successfully installed django-2.2.6, pytz-2019.3 and sqlparse-0.3.0. I then set up the correct directory to my working folder, I used django-admin startproject mysite and finally python manage.py runserver. System check identified no issues (0 silenced). When I try to connect to the local machine on http://127.0.0.1:8000/ it loads up just fine, but then I get this output in cmd and it will not let me do anything else: [26/Oct/2019 23:29:47] "GET / HTTP/1.1" 200 16348 [26/Oct/2019 23:29:47] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [26/Oct/2019 23:29:47] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [26/Oct/2019 23:29:47] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [26/Oct/2019 23:29:47] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184 Not Found: /favicon.ico ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 50150) Traceback (most recent call last): File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in … -
update throwing TypeError: serializer.update() got an unexpected keyword argument 'data'
I'm trying to update an already db-saved object once it has successfully sent a message. it calls the update() method of the serializer class in order to achieve this. This is the model that will have it's instance updated: class SMSMessages(models.Model): sms_number_to = models.CharField(max_length=14) sms_content = models.CharField(max_length=160) sending_user = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="user_that_sent") sent_date = models.DateTimeField(auto_now=True) delivery_status = models.BooleanField(default=False) class Meta: verbose_name_plural = "SMSMessages" def __str__(self): return str(self.sending_user) This is the serializer class I'm using: class SMSMessagesSerializer(serializers.ModelSerializer): """ A class for serializing the SMSMessages model's data. It sub-classes the ModelSerializer class from serializer's module. """ class Meta: model = SMSMessages fields = '__all__' def update(self, instance, validated_data): """ This method is used to update an instance of the SMSMessages's delivery_status attribute. It get's the value for delivery_status from the input parameter, updates the specific instance of the SMSMessagesSerializer, saves that instance and returns it. """ instance = self.get_object() instance.delivery_status = validated_data.get('delivery_status', instance.delivery_status) instance.save() return instance and this is the APIView class that has the POST method that will update the if the message is successfully sent: class SMSView(APIView): """ This class is responsible for all the method operations of an sms. It provides implementations for the GET, POST, and OPTIONS methods. … -
Django template: change id for form in the for loop
I have a Model and a Form as below class Comment(models.Model): post = models.ForeignKey('Post', related_name='comments',on_delete=models.CASCADE,) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) slug = models.SlugField(unique=True, default=uuid.uuid4) class CommentForm(forms.ModelForm): class Meta: model = models.Comment fields = ('text',) widgets = { 'text': forms.TextInput(attrs={ 'id': 'comment-text', 'required': True, 'placeholder': 'Say something...'}), } And in the Django template, I want to use this form several times in a for loop but each iteration I want to change the id of the text in the loop. Currently I am using like below code {% for post in post_queryset %} {% csrf_token %} {% bootstrap_form formComment %} {% endfor %} can someone help me to change the code so that id will change each time in the loop. -
Pagination where search and results are on the same page
I have a template where the users pass a query and select a couple of checkboxes (these can range from 1-100). Then, my view does the following: def search(request): results_list = search(request.GET.get("q", ""), request.GET.getlist("c")) # Pagination paginator = Paginator(results_list, 10) page = request.GET.get("page") results = paginator.get_page(page) return render( request, "web/search/show.html", { "query": query, "results": results, }, ) The issue arrises because both the search and the presentation of the results happen on the same page. Therefore, when I want to include pagination, in my template, I have to do the following: <div class="pagination"> <div class="step-links"> {% if results.has_previous %} <a href="?page={{ results.previous_page_number }}&{{request.GET.urlencode}}" class="prev-page-link">Previous</a> {% endif %} {% if results %} <span class="current"> Page {{ results.number }} of {{ results.paginator.num_pages }} </span> {% endif %} {% if results.has_next %} <a href="?page={{ results.next_page_number }}&{{request.GET.urlencode}}" class="next-page-link">Next</a> {% endif %} </div> </div> Please consider the usage of request.GET.urlencode because when I go to either the previous or next page I have to pass the same query and checkboxes. However, this creates a bug when the user goes past the second page, because the ?page=3&page=2 keep on piling up. Can someone point me in the right direction for solving this issue? -
Loading url content (Django template) into a <div> with jQuery not working
<body> <script>function lol () { $("#content").load("banned_profiles") } </script> <div class="side_bar_links"> <div id="side_bar_links"> <ul> <li><a href="javascript:lol();" id="banned_profiles">Banned Profiles</a></li> </ul> </div> </div> <div id="content" class="content"> </div></body> The above snippet is self-explanatory. I am trying to load content - basically another Django template inside a , using the load() function . It doesn't work . I assume load("banned_profiles") makes a call to the URL as if it would be written on href="banned_profiles" value. (Which works but redirects and refreshes the whole page). banned_profiles view is constructed in the Django backend and can be normally called . I have also tried load('http://localhost:8000/admin/banned_profiles') - doesn't work. I have tried many other options, like to extend the template, which then works, however, it doesn't load only when the link is pressed, but loads concurrently with the entire page and doesn't display within the given . I know this has been asked a thousand times, but I have search pretty much everything on google and still no success. Any ideas? Many Thanks. -
Next request does not contain COOKIE with sessionid value with Django Session middleware
I am not sure why I dont see the cookie value of sessionid in my next request after creating a new session. This is the SECOND call from my frontend: fetch('http://127.0.0.1:8000/game', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({'name': player.name, 'email': player.email}) }) In my first call to my view I created a session and responded with some data and a 200. I can see the session be created in my Session table in my DB. @csrf_exempt @api_view(['GET']) def shuffle(request): if request.method == 'GET': request.session['selected'] = [] request.session['words'] = [] if not request.session.session_key: request.session.create() print(request.session.session_key) response = Response(data={'dice': 1}, status=status.HTTP_200_OK) else: response = Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) return response I can see this session_key in my console and I see it in my developer tools cookie as well. However, on my next request to another view, I do not see anything in my request.COOKIE as well as nothing in my request.session.session_key @csrf_exempt @api_view(['POST']) def game(request): if request.method == 'POST': print(request.session.session_key) # None <--- print(request.COOKIE) # None <--- response = Response(status=status.HTTP_201_CREATED) return response -
Setting Redis password breaks Django Channels Despite providing channels the password
I want to start of by saying I was following this digital ocean guide to setup and secure Redis. After setting the Redis password, it breaks the notification system I had implemented. So I tried using the options setting to provide the password as such: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'OPTIONS': { "PASSWORD": 'pass', }, 'CONFIG': { 'hosts': [('localhost', 6379)], } } } Despite this, it is erroring: Exception Value: NOAUTH Authentication required. Traceback: Environment: Request Method: POST Django Version: 2.1.7 Python Version: 3.6.8 File "/home/user/project/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/user/project/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/user/project/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/project/env/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/user/project/project-name/textcorrect/decorators.py" in wrapper 38. return func(self, *args, **kwargs) File "/home/user/project/project-name/journal/views.py" in correction 196. return catch_correction(request, pk) File "/home/user/project/env/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/user/project/project-name/textcorrect/decorators.py" in wrapper 38. return func(self, *args, **kwargs) File "/home/user/project/project-name/journal/views.py" in catch_correction 229. create_notification({'creator': request.user, 'receiver': Post.objects.get(id=pk).user_id, 'type_id': 1, 'post_id': pk}) File "/home/user/project/project-name/notifications/views.py" in create_notification 21. send_count(data.get('receiver')) File "/home/user/project/project-name/notifications/views.py" in send_count 31. {"type": "receive", "text": n_count, "notification": notification.first().notification_text}, File "/home/user/project/env/lib/python3.6/site-packages/asgiref/sync.py" in __call__ 79. return call_result.result() File "/usr/lib/python3.6/concurrent/futures/_base.py" in result 425. return … -
Understanding inheritance in Django
I am trying to understand some basics in django inheritance - I'm sure it is something trivial, buy I just can't get it. I've got my CartItemForm(forms.ModelForm) and I override init method to get user from post.request, like that: def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super().__init__(*args, **kwargs) And it works, but I don't really get why it doesn't work when I inherit init method first: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.request = kwargs.pop('request', None) init() got an unexpected keyword argument 'request' What am I missing here? -
Trouble Serializing a many-to-many field
Before this gets marked as a duplicate, I've looked at the following questions: Django Rest framework Serialize many to many field Django rest framework serializing many to many field No results are being shown for payins when I test. serializers.py class PayinsSerializer(serializers.ModelSerializer): class Meta: model = Payins fields = '__all__' class UserStokvelSerializer(serializers.ModelSerializer): payins = PayinsSerializer(many=True) class Meta: model = Stokvel fields = '__all__' models.py class Payins(models.Model): payin_date = models.DateField(default=timezone.now) payin_by = models.ForeignKey(User, on_delete=models.CASCADE) stokvel_payin = models.ForeignKey('Stokvel', on_delete=models.CASCADE, related_name="payin_user") payin_amount = models.IntegerField() def save(self, *args, **kwargs): stokvel = Stokvel.objects.get(id = self.stokvel_payin.id) stokvel.balance += self.payin_amount stokvel.save() super(Payins, self).save(*args, **kwargs) class Stokvel(models.Model): stokvel_name = models.CharField(max_length=55) balance = models.IntegerField(default = 0) payouts = models.ManyToManyField(Payouts, related_name="stokvel_payouts") payins = models.ManyToManyField(Payins, related_name="stokvel_payins") group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="stokvel_group_admin") users = models.ManyToManyField(User, related_name="stokvel_users") invite_key = models.CharField(default = secrets.token_hex(15), max_length=55) -
Searching in django, query
Hei, I want to create an app where an user can search ingredients by their names, but when i search for ingredient and put enter then I get blank side without any information what is wrong. My models: from django.db import models class Ingredient(models.Model): ingredient_name = models.CharField(max_length=250) def __str__(self): return self.ingredient_name class Recipe(models.Model): recipe_name = models.CharField(max_length=250) preparation = models.CharField(max_length=1000) ingredients = models.ManyToManyField(Ingredient) def __str__(self): return self.recipe_name my views: from django.shortcuts import render from django.db.models import Q #new from .models import Recipe from .models import Ingredient def drink_list(request): template = "drinks/drink_list.html" return render(request, template) def search_results(besos): query = besos.GET.get('q') q = Q() for queries in query.split(): q |= (Q(ingredient_name=queries)) results = Ingredient.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context) -
User Session Tracking Middleware in Django
I'm trying to set up a basic session counter for users who log into the site, so I can know how active they are. I want it to run not just when they fill out the login form, but if they come back already logged in. I'm separating session saves by 1 hour, counting sessions that happen within the same hour as the same session. The middleware: (1) Saves a new session to the UserSession object and (2) increments total_visits by 1 on the UserProfile object. My issue is that it's saving 2 sessions per visit, and increasing the count by two. So basically it's running twice before setting the cache. in settings.py MIDDLEWARE = ( ... 'my_app.middleware.LastUserActivityMiddleware', ) which points to this middleware def LastUserActivityMiddleware(get_response): def middleware(request): """ Save the time of last user visit """ response = get_response(request) if request.session.session_key: key = "recently-seen-{}".format(request.session.session_key) recently_seen = cache.get(key) # is_authenticated hits db as it selects user row # so we will hit it only if user is not recently seen if not recently_seen and request.user.is_authenticated: try: user_profile = UserProfile.objects.get(user=request.user) user_profile.total_visits= F('total_visits') + 1 user_profile.save() except: UserProfile.objects.create(user=request.user, total_visits=1) UserSession.objects.get_or_create(user=request.user, session_key=request.session.session_key) visit_time = 60 * 60 # wait one hour before logging … -
Using '_id' in Django
I am a bit confused how Django handles '_id' property when we use ORM with some models that use foreign key. For example: class CartItem(models.Model): user = models.ForeignKey('accounts.CustomUser', related_name='carts', on_delete=models.CASCADE, verbose_name='User') product = models.ForeignKey('pizza.Product', related_name='carts', on_delete=models.CASCADE, verbose_name=_('Product')) quantity = models.SmallIntegerField(verbose_name=_('Quantity')) And when I use ORM with 'filter' I can easily use something like: CartItem.objects.filter(user=1, product=1, quantity=1) And Django kind of 'see' that I refer to 'id', but when I use exacly the same line of code, but with 'create' instead of 'filter': CartItem.objects.create(user=1, product=1, quantity=1) Then it throws an error saying: Cannot assign "1": "CartItem.user" must be a "CustomUser" instance. And to create it I need to use: CartItem.objects.create(user_id=1, product_id=1, quantity=1) Why is that? Is there some rule here that I don't understand? -
How to create multiple models from the same form in Django
I have a create view used to make a quiz that has the title, author, etc but my quizzes are made up of answer models that are linked to question models that are then linked to this quiz. How do I make a form for creating a whole quiz, including the questions and correct answers, from this? class QuizCreateView(LoginRequiredMixin, CreateView): model = Quiz fields = ['title', 'video_link', 'question_amount'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I use crispy forms in the template {% extends "quiz_app/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Quiz</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-blue" type="submit">Submit</button> </div> </form> </div> {% endblock content %} TIA -
Queryset object in Django form not iterable
I'm trying to get the form to create the fields based on what exam page the user is on. In the error page all local variables have the correct value for form and view, but i keep getting "ExamQuestion" object not iterable and an error at line 0 of template. It also highlights the render() at line 44 in the view as the source of the problem. If I change line 28 from "exam__name=exam_name" to "exam__name="exam_name"", basicly turning the variable into a str, the page runs but no data is passed. In the error console choice_list shows querysets as individual list items as it should for forms.py How do I make the object ExamQuestion iterable? Ive been stumped for a week now. I've written a hundred ways at this point. I know it's listing questions instead of answers for the questions, I'm just trying to get it to load ANY queryset and freaking run at this point. view def exampage(request, exam_name): exams = Exam.objects.all() questionlist = ExamQuestion.objects.filter(exam__name=exam_name) choicelist = ExamChoice.objects.filter(question__exam__name=exam_name) form = ExamTest(request.POST, exam_name=exam_name) if request.method == "POST": if form.is_valid(): #form.save() #choice = form.cleaned_data.get('choice') return redirect('exampage.html') return render(request, 'exams/exampage.html', {'exams': exams,'questionlist': questionlist, 'exam_name': exam_name, 'choicelist': choicelist, 'form': form, 'choice': choice}) … -
Django app doesn't recognize .env file, I tried to set it up through the os, Django-environ, and dotenv but nothing worked
I set up a new django app in a virtual environment and tried to use a .env file with it for the secret key and the database url, however I can't manage to make the django app read the .env file. I've tried first with os.environ, tried to set a direct path, tried with dotenv (both python-dotnev and django-dotnev, seperately) and last with Django-environ. I tried putting the .env file is in the same folder, the parent folder, the venv folder, but nothing worked. In myapp/settings.py I have: import os import environ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) env = environ.Env() environ.Env.read_env() SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG') ALLOWED_HOSTS = [] And then in the same folder I have ".env" file: Debug=True SECRET_KEY='some-secret-key' I tried adding "export" before Debug and SECRET_KEY but it didn't make any difference. I constantly get this error when I run python manage.py runserver: raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable What am I missing? What step did I not do? Does it not work because the app runs in a virtual envirnoment? -
Comparing strings in SQL, where the same two records are never compared again
I am currently working on a capstone project for an IT degree and could use some guidance. My stack for this project is windows>python>django>MySQL I have an article table and news source table. I am comparing the string content of each article against each article in the database. My problem is that I only want to compare Article "A" to Article "B" once no matter how many times the comparison script is run. I am assuming that I would populate the relationship table with foreign keys from each of the articles and then cross-check the relationship table for that exact article FK combination? Not needing exact coding examples but the logic in how to tackle this problem. Thanks, Stackoverflow community. Django SQL Models -
I get a ' no module named django ' error on heroku only when i try to submit an email form yet locally it works just fine
When I pip freeze on heroku console i find that django has been installed. When i try to submit the form locally on my computer the submission is successful with no errors. Views.py ''' @login_required(login_url='/accounts/login/') def b_contact(request): c_form = ContactForm if request.method == 'POST': c_form = ContactForm(data=request.POST) if c_form.is_valid(): email = c_form.cleaned_data['email'] subject = c_form.cleaned_data['subject'] message = c_form.cleaned_data['message'] send_mail(email, message, subject, ['be.rightmuk@gmail.com'], fail_silently=False) messages.success(request, f'Your message has been sent!') return redirect('buyer_home') else: email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') context = { 'c_form': c_form } return render(request, 'buyer/contact.html', context) ''' forms.py class ContactForm(forms.Form): email = forms.EmailField(label='Your Email') subject = forms.CharField(required=True, max_length=150) message = forms.CharField(widget=forms.Textarea, required=True) tepmplate <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ c_form|crispy }} </fieldset> <button class="btn btn-default" type="submit">Send </button> </form> requirements.txt dj-database-url==0.5.0 Django==2.0 django-bootstrap3==11.0.0 django-bootstrap4==1.0.1 django-braces==1.13.0 django-crispy-forms==1.7.2 django-heroku==0.3.1 django-model-utils==3.2.0 django-progressive-web-app==0.1.1 django-registration==2.4.1 django-tinymce==2.8.0 djangorestframework==3.9.4 gunicorn==19.9.0 This is the error ModuleNotFoundError at /seller/contact/ No module named "'django" Request Method: POST Request URL: https://sakka.herokuapp.com/seller/contact/ Django Version: 2.0 Exception Type: ModuleNotFoundError Exception Value: No module named "'django" Exception Location: <frozen importlib._bootstrap> in _find_and_load_unlocked, line 953 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.8 Python Path: ['/app/.heroku/python/bin', ' /app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Thu, 24 Oct 2019 15:06:42 +0300 This … -
Django Receiving Message from SQS
I have a Django application that runs a process once a day using Celery and SQS and saves the files to S3. I used this tutorial to setup Django, Celery and SQS. That works out well when the flow is Django --> SQS --> Celery --> S3 However, in addition to saving files to S3, I need to be able to run a process when the S3 Bucket receives files from another application (it's a shared S3 Bucket). In that case the flow is S3 --> SQS --> Celery --> Django From what I read in the documentation it is possible to send a notification when a new document is created in S3 using SQS. So if I set that up it takes care of the S3-->SQS portion. What I'm not clear on is how this message gets passed from SQS to Celery and then to Django to perform what I need to do with the new object: This would be the final process: 1- A new File gets saved to S3 2- A notification saying a new file was saved in S3 with the name of the file gets sent using SQS 3- SQS notifies the Celery worker a … -
display a list of items in a select box in my html template in django 2.2
I have a list of departments i want to be shown in a select drop-down but its not shown? Its a duty-log App and want the user to be able to select the department from the drop-down. here's my views.py def index(request): # the index view logs = Dutylog.objects.all() # quering all logs with the object manager departments = Department.objects.all() # getting all departments with object manager if request.method == "POST": # checking if the request method is a POST if "taskAdd" in request.POST: # checking if there is a request to add a logo title = request.POST["description"] # title date = str(request.POST["date"]) # date department = request.POST["department_select"] # department content = title + " -- " + date + " " + department # content Log = Dutylog(title=title, content=content, due_date=date, department=Department.objects.get(name=department)) Log.save() # saving the log return redirect("/") # reloading the page if "taskDelete" in request.POST: # checking if there is a request to delete a log checkedlist = request.POST["checkedbox"] # checked logs to be deleted for log_id in checkedlist: Log = Dutylog.objects.get(id=int(log_id)) # getting log id Log.delete() # deleting logo return render(request, "index.html", {"logs": logs, "department": departments}) here''s my models.py class Department(models.Model): # The Category table name that … -
Django return result set from postgreSQL function
I have a postgreSQL function (named changed_permissions_for_role) that returns a TABLE. When I query the function in DataGrip, it works perfectly (i.e. I get all rows that I am expecting). In DataGrip, I am doing this: SELECT * FROM changed_permissions_for_role(6, 7) When I try to do the same thing in my Django project, I get nothing!?!? This is what I am doing in the Django project: with connection.cursor() as cursor: permissions = cursor.execute("SELECT * FROM changed_permissions_for_role(%s, %s)", [role.base, pk]) return render(request, 'roles/edit.html', {'permissions': permissions}) What am I doing wrong? I am unable to debug the project to try to see if I can figure it out myself but my PyCharm debugger suddenly doesn't work anymore :( (Thanks for your time) -
Order choices by user
I'd like to order a choicefield on a form in alphabetically order by user models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) busname = models.CharField(max_length=60) forms.py self.fields['user'].choices = tuple([(t.user.id, t) for t in UserProfile.objects.all().order_by('user')]) Unfortunately, this isn't working. The order is coming out by user.id Thanks! -
Django ternary models relationship with constraints
As part of a Django online platform that offers online courses, course authors are free to include exercises from a public exercise repository. Each course has its own chapters and is free with how to organize the exercises in chapters. An exercise in a course can be part of zero or one chapter. When a chapter in a course is deleted, the exercises in it just go back to the status of no chapter assigned. What I have so far : class Exercise(models.Model): title = models.CharField(max_length=30) class Course(models.Model): title = models.CharField(max_length=30) exercises = models.ManyToManyField(Exercise) class Chapter(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) title = models.CharField(max_length=30) The problem: There is no link between exercises and course chapters so far, it isn't clear to me how to do it in a proper way taking into consideration the constraint that an exercise in a chapter should be in the course as well. -
How to use pendulum as a base datetime library with Django?
I would like to use pendulum as a base datetime library with Django. So, a DateTimeField should work with pendulum objects, not datetime objects. I have followed an example on pendulum's docs page and created a special field: import pendulum from django.db.models import DateTimeField as BaseDateTimeField class DateTimeField(BaseDateTimeField): def value_to_string(self, obj): val = self.value_from_object(obj) if isinstance(value, pendulum.DateTime): return value.format('YYYY-MM-DD HH:mm:ss') return '' if val is None else val.isoformat() ...and used that in my models.py: class Task(models.Model): title = models.CharField(max_length=100) description = models.TextField() done = models.BooleanField() due_date = BaseDateTimeField() def is_today(self): return self.due_date.in_timezone('utc').date() == pendulum.today('utc').date() ...however I'm getting an error: 'datetime.datetime' object has no attribute 'in_timezone' ...which obviously means that Django treats due_date still as a datetime object, not a pendulum object. Is there a possibility of switching to using pendulum as a base datetime library with Django? P.S. I think something is wrong with that docs snippet, value appears out of the blue, but I don't think that this is the cause of the problem. -
Using postgis and mongodb django
I use django (2, 1, 5, 'final', 0). My problem, i try to store an address model in postgresql, all the others models (auth, products...) in mongodb engine with the djongo package. the models stored in app => geolocalise : class Address(models.Model): line1 = models.CharField(max_length=150) line2 = models.CharField(max_length=150, blank=True) postalcode = models.CharField(max_length=10) city = models.CharField(max_length=150) country = models.CharField(max_length=150, default="France") #the postgis entry location = models.PointField(null=True) latitude = models.FloatField( default=0) longitude = models.FloatField( default=0) description = models.TextField(max_length=1024,blank=True) #user = models.ForeignKey('User', related_name='user', on_delete=models.CASCADE) def __str__(self): return "{0} - {1} - {2}".format(self.line1, self.postalcode, self.city) here my settings py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'DBNAME', 'USER': 'USER', 'PASSWORD': 'PASSWORD'}, 'postgresql': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'DBNAME', 'USER': 'USER', 'PASSWORD': 'PASSWORD'}} But when i do my migrations i don't know why the database is store in mongodb. I've try a configuration in a router.py which i found on stackoverflow but it's isn't working: class GeolocaliseRouter(object): def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == 'geolocalise': return 'postgresql' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == 'geolocalise': return 'postgresql' return None def allow_relation(self, obj1, obj2, … -
How to add a domain to your localhosting web server
I made a web server with django that i'm hosting on my PC. I have port forwarded my web server to my routers port 80 and can access it just fine from the outside using the Wan address+:80. My question is how i can access my web server through a domain and not my Wan address? For example how can i use http://www.123examplesite.com to access my web server instead of http://123.123.1.123:80? I already have a domain name registered (i used freenom.com for that)