Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running celery beat on windows
I work on a Celery beat task within a django project which sends emails periodically. The worker is a RabbitMQ In a development environment I use the following commands to starting the Scheduler and worker process, respectively: celery -A proj beat --loglevel=info celery -A proj worker -- loglevel=info For the above I need to activate python virtual environment and run each command in separate CMD window and it worked perfectly. However, bringing it to a production environment (daemon) on Windows is not that easy. In this post Daemonising Celery on Windows launch Celery using a batch file and configure Windows Task Scheduler to run the Celery service periodically. Which seems to be a simple solution, although I don't know how advisable My question is, what would be the correct commands from the batch file to activate the virtual environment, execute the commands described in number 1) and 2) and finally stop the services. I know it is simple but I don't know what the correct commands are. If anyone can help me I would be very grateful. The following are the steps to activate the virtual environment, run celery beat and the worker and stop the process when it is … -
Is Django better or C# for website backend?
Well... I am working on a website and I am completely new to programming and Web-designing. I have made a website but it is only static for now and I want to implement a backend. I know Python quite well but I am new to C# and learning it. The problem or rather a question is that should I use Django(Python) for back-end development or should I wait and learn C# and then use C# as the back-end? I also had a thought of using PHP as my back-end, but I think Python would be more powerful. And I have read on Google that if I make the back-end in C# it will only run on Windows Server and not on Linux, Is it true? Thanks in Advance. -
Where is the result stored in Redis and how long will the result be stored before removed?
Currently, we are trying to figure out which plan we need to use for heroku-redis in our website. But before making any decision on that, We are trying to figure out how does the clients work in the redis. We've done some testing, and understand that clients are showing each commands that redis is calling; however, there are something we are still confused about and would be very appreciate if we could get some help on that! (If the timeout=0) It makes sense that every time when I refresh the website, the number of clients will be increased, most likely it is "get" and "unsubscribe" (even though other commands are being used, such as "subscribe" and "multi", etc. but they are not showing in the client list, which makes me a little confused since we set the timeout to 0, so it is supposed to be in the clients list, but it is not). However, when the number of "get" clients reach to 4 or 5 (depends), and when I start to refresh the page again, the number of "get" clients stopped increasing, and it seems redis is reusing it (I realized that because I see the idle time decrease … -
Using multiple admin.py files for Django rest?
I currently have 2 admin.py files. project/admin.py project/pages/basicpage/admin.py I would like to use the registered classes inside the second admin.py along with the first admin.py such that they can both be reached at the same admin endpoint. FILE ONE: project/admin.py from django.contrib import admin from project import models from project.pages.basicpage import admin as BP_admin @admin.register(models.Test) class TestAdmin(admin.ModelAdmin): pass FILE TWO: project/pages/basicpage/admin.py from django.contrib import admin from project import models @admin.register(models.Platform) class PlatformAdmin(admin.ModelAdmin): pass @admin.register(models.Type) class TypeAdmin(admin.ModelAdmin): pass In file one, I have imported the second admin as BP_admin, not that it is used yet. However when I access my http://127.0.0.1:8000/admin endpoint, understandably I only can view the "Test" class that is registered in the first file. Any idea how to get my other 2 classes from my second file registered to the first file's endpoint? Thanks! -
How to emulate Postgres Django distinct() with SQLite backend
I'm racking my brain on how to form this filter query using Django's Querysets. The following filter query returns objects containing the following fields: candidate, informationField, option. selected_options = CandidateInformationListOptionsAnswer.objects.filter( candidate=candidate, informationField=element ) In selected_option, every object will have the same values for candidate and informationField. However, the option fields in the objects in the QuerySet have duplicates, when they should be unique. Therefore, I want to run the equivalent of a .distinct("option") call on selected_options, but my DB backend is not Postgres, so I don't have the ability to pass in field names into a QuerySet.distinct() call. How would I structure my .filter() queries to get a QuerySet of objects that are distinct for a particular field with a SQLite backend? -
Merge duplicate values in django query
I have a SQL query but I want to know, how can I write in Django format (PostgreSQL). I'm new with django :) Suppose, we have data in a table like this. 1: Color: Pink, Size: 1M 2: Color: Pink, Size: 2M 3: Color: Red, Size: 1M 4: Color: Red, Size: 3M 5: Color: Yellow, Size: 2M Expecting output Pink Red Yellow I'm getting output with the below query. But I want to know, how can I query & merge duplicate values in django // id = product_id colors = Variants.objects.raw('SELECT * FROM product_variants WHERE product_id=%s GROUP BY color_id',[id]) -
Retrieving multiple objects from Django REST API
I made a Django backend using the REST api using many-to-many relationships. I was wondering what is the best way to get all of the objects that a certain object is pointing to. So in my case there are decks that have cards, and the decks point to the cards' indexes. Cards can belong to multiple decks. What I do is retrieve all decks, then for a specific deck I will traverse a for loop for each card index, and call the api and retrieve the card and add it to a local array. I don't have any experience with backends before this, so I'm wondering how I could efficiently set up how my frontend calls the backend. I wrote my frontend using react-native, and make the calls with axios. -
Django Javascript Error: missing : after property id
I am getting this error when pressing the like button on my posts. It was working while showing the error for a while but now it won't work so where do i need to put the colon? full error: Uncaught SyntaxError: missing : after property id i have marked the where i think the error is pointing to(it's near the bottom) $(document).ready(function() { $('.like_form').submit(function(e){ e.preventDefault() const post_id = $(this).attr('id') const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() const trimCount = parseInt(likes) var likeElement = document.getElementById(`like_button${post_id}`); var dislikeElement = document.getElementById(`dislike_button${post_id}`); var likeElementAd = document.getElementById(`like_button_ad${post_id}`); var dislikeElementAd = document.getElementById(`dislike_button_ad${post_id}`); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'post_id': post_id, }, success: function(response){ if (likeElement.classList.contains("liked_post")){ res = trimCount - 1 likeElement.classList.remove("liked_post") if (likeElementAd){ likeElementAd.classList.remove("liked_post") } } else if (!$(this).hasClass("liked_post")) { res = trimCount + 1 likeElement.classList.add("liked_post") dislikeElement.classList.remove("disliked_post") if (likeElementAd){ likeElementAd.classList.add("liked_post") } if (dislikeElementAd){ dislikeElementAd.classList.remove("disliked_post") } } $(`.like_count_ad${post_id}`).text(res +' Likes') $(`.like_count${post_id}`).text(res +' Likes') }, error: function(response){ console.log('error', response) } }) }) $('.dislike_form').submit(function(e){ e.preventDefault() const post_id = $(this).attr('id') const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() const trimCount = parseInt(likes) var likeElement = document.getElementById(`like_button${post_id}`); var dislikeElement = document.getElementById(`dislike_button${post_id}`); var likeElementAd = document.getElementById(`like_button_ad${post_id}`); var dislikeElementAd = document.getElementById(`dislike_button_ad${post_id}`); $.ajax({ type: 'POST', url: … -
Django Celery Worker fetches old data
When I update a field on a Django model instance, save it, and try to fetch this model instance from within a celery worker then often it gives me the old value. If, however, I fetch the same model instance from outside a celery worker then I get the right value. For the database I use PostgresSQL. celery==3.1.25 Django==1.10.8 I know that the celery & Django version are outdated, but for this project it's currently not possible to bump it. Does anyone know what might be causing this behaviour? -
ForeignKey updates aren't cascading on Django created tables in Postgres
This is the error that I get when I try to update the value in the "parent" table that the foreign key is looking at in a related table: ERROR: update or delete on table "product" violates foreign key constraint "pd_family_product_guid_ada83db3_fk_product_guid" on table "pd_family" DETAIL: Key (guid)=(902d30b8-26ba-ea11-a812-000d3a5bbb60) is still referenced from table "pd_family". SQL state: 23503 This is what I have for my models: class Product(models.Model): guid = models.UUIDField(primary_key=True) product = models.CharField(max_length=10) year = models.IntegerField() previous_product_name = models.CharField(max_length=10) class StandardProductFieldsMixin(models.Model): product_guid = models.ForeignKey('Product', on_delete=models.CASCADE, db_column='product_guid') class Meta: abstract = True class ActiveFieldMixin(models.Model): active = models.BooleanField() class Meta: abstract = True class Family(StandardProductFieldsMixin, ActiveFieldMixin): new_code = models.IntegerField(null=True) code = models.DecimalField(max_digits=20, decimal_places=2) title = models.CharField(max_length=255) desc = models.TextField(null=True) fam_desc = models.TextField(null=True) When I try to change a value of guid in Product, my expectation is that it would automatically change it in Family as well. I guess I was under the wrong impression. Do I need to do something additional in the model? Looked at the documentation for something like on_update, but not seeing that either an **options or as a parameter for models.ForeignKey. -
How to add custom method in django forms
I am new to django, and I am creating a vacation application. I want to be able to when I create a new trip, the user that created the trip becomes a member of that trip. here is my models.py file: class Trip(models.Model): trip_name = models.CharField(max_length=255,unique=False) start_date = models.DateField(default=datetime.date.today) end_date = models.DateField(default=datetime.date.today) slug = models.SlugField(allow_unicode=True,unique=True) members = models.ManyToManyField(User,through='TripMember') def __str__(self): return self.trip_name def save(self,*args,**kwargs): self.slug = slugify(self.trip_name) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('trips:single',kwargs={'slug':self.slug}) class Meta: ordering = ['start_date'] class TripMember(models.Model): trip = models.ForeignKey(Trip,null=True,related_name='memberships',on_delete=models.SET_NULL) user = models.ForeignKey(User,null=True,related_name='user_trips',on_delete=models.SET_NULL) def __str__(self): return self.user.username class Meta: unique_together = ('trip','user') this is my forms.py file: class TripCreateForm(forms.ModelForm): class Meta: fields = ('trip_name','start_date','end_date') model = Trip def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["trip_name"].label = "Trip Name" self.fields["start_date"].label = "Start Date" self.fields["end_date"].label = "End Date" here is my views.py file: class CreateTrip(CreateView): form_class = TripCreateForm template_name = 'trips/trip_form.html' and my trip_form.html page: <form action="{% url 'trips:create' %}" method="post" id='tripForm'> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn-primary btn-large" value="Create"> {% endblock %} Where would I put the code to set the user as a tripmember and why?Also, if there is a better way to have set this up please let me know! I was gonna … -
Setup the HstoreField type Django
I have need to store an Array inside my Django model. I heard about the ArrayField but I don't understand, how to install it. I don't see how I can install the Hstore extension needed in my Django project. Any help would be nice... I don't find any tutorials on this extension :/ Thanks -
Can the User model be overridden to make the email field required?
For my application, the email field in the Django User model should be required, but by default it's optional. I searched this question but most answers I found were talking about making the email field required in the customised UserCreationForm for example: class CustomUserForm(UserCreationForm): """Provide a view for creating users with only the requisite fields.""" class Meta: model = User # Note that password is taken care of for us by auth's UserCreationForm. fields = ('username', 'email') def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['email'].required = True but I want to make the email mandatory in the User model as well because I was thinking maybe ModelForm are a frontend thing and the required condition maybe be turned off by the user by using the chrome dev tools, am I wrong? Will making the email required in ModelForm is same as making it required in the user model as well, or can I override the user model to make the email required? -
Django Create Recurring Payments
Good day, I have two models, one for the destitute and the other for credit payments to be submitted to a bank for deposit into the destitute's acc. I need some guidance creating a function that loops through the Destitute table, creates recurring payments every month, and records them in the Credit table. Logic is if the destitute is above the age of 50 they get paid 2500k if below the age of 50 they get paid 2000k. If there is a Django package that can help achieve that would be great. class Destitute(models.Model): SEX_TYPE = (("male", "male"), ("female", "female")) name = models.CharField(max_length=100) acc_no = models.CharField(_("Bank Account"),max_length=50) age = models.PositiveIntegerField(default=1) sex = models.CharField( _("Transaction Source"), max_length=64, choices=SEX_TYPE) created_on = models.DateTimeField(_("Date Joined"), auto_now_add=True) def __str__(self): return self.name class Credit(models.Model): credit_title = models.CharField(_("Payment Title"), max_length=50) payee = models.ForeignKey( Destitute, related_name="destitute_paid", on_delete=models.SET_NULL, null=True, blank=True) total_amount = models.DecimalField( blank=True, null=True, max_digits=12) payment_date = models.DateField(blank=True, null=True) def __str__(self): return self.credit_title -
how to hide the value for the password field in Django Rest Framework API view
click here for the image in the attached image for the password field I need "****" instead of "pass", is there any password widget available for Serialzers? -
Django table rendering blank rows
I've searched far and wide, and haven't come up with a solution despite this probably being a simple fix. Models.py: class Leaderboard(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Score(models.Model): leaderboard = models.ForeignKey(Leaderboard, on_delete=models.CASCADE) player_name = models.CharField(max_length=25) score = models.IntegerField() time_set = models.DateTimeField(null=True, blank=True) def __str__(self): return f"{self.player_name} - {self.leaderboard} [{self.score}]" views.py def index(response, name): # ls = Leaderboard.objects.get(name=name) sorted = Leaderboard.objects.filter(name=name).order_by('-score') return render(response, "highscores/leaderboard_ranks.html", {"ls": sorted}) And the relevant template part of the code. {% for item in ls %} <tr> <td></td> <td>{{item.player_name}}</td> <td>{{item.score}}</td> <td>{{item.time_set}}</td> </tr> {% endfor %} And this just outputs blank rows in the table. What am I missing? -
Django - How to carry the filters to the next view?
I imagine something like this is possible in Django, but I don't know how to implement it: I have a TableView, which has filters to filter the displayed queryset. I, then, have a DetailView which you can access from the TableView, to see the details of each element in the queryset. The DetailView has a form, which uses the POST method. I can successfully send the form, and redirect to the TableView after the POST call. My question is, how can I make it so that after the user calls the POST method in the DetailView, and it redirects again to the TableView, the TableView keeps whichever values were on its filters? I imagine I would have to either get access to the full request on the TableView (because it includes the ?param1=?param2= etc.), or be able to send the values in the filters when I call the DetailView. -
Can not create Virtual Enviroment for Django Freamwork
C:\Users\Slavi\Documents\Django>python -m venv env Python I am triing to create virtual enviroment for django freamwork using the cmd in windows. When i try to create it it do not create anything just write Python on the next line and thats it....I am new at the Django and in the Python so please help. -
how can I display just plain text among posted information which have images, tables from CKEditor in Django?
As same as stack overflow does in a homepage, showing questions without images just with tags, I want my blog site to show just a title and a header in a list of blog posts page. the uploaded image ruins css card section and tables display half of it. so I would rather display just plain text. I am currently using Django(3.1.5), CKEditor. My question is; How to get a plain text from ckeditor?, how to catch a image uploaded from CKEditor, if I can, can I save those images into the model(ImageField or FileField)? -
Django forms - Allow a user to create a group for other users
I am trying to let a user create a "club" (basically a group) where the user later on can add users to. Currently it only displays the HTML text and the button, but no text field. Any suggestions would be appreciated since I am fairly new to forms. Model class Club(models.Model): owner = models.CharField(max_length=30) topic = models.CharField(max_length=30) start = models.DateTimeField(verbose_name='start date', auto_now_add=False) end = models.DateTimeField(verbose_name='end date', auto_now_add=False) account = models.ManyToManyField(Account) Views @login_required def add_club(request): if request.method == "POST": form = AddClubForm(request.POST, instance=request.user) print(form) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) else: form = AddClubForm(instance=request.user) return render(request, 'page/club.html', { "form": form, }) Form class AddClubForm(forms.Form): owner = forms.CharField(required=True) topic = forms.CharField(required=True) start = forms.DateField(required=True) end = forms.DateField(required=True) class Meta: model = Club fields = ( 'owner', 'topic', 'start', 'end', ) Template <form method="POST" action=""> {% csrf_token %} <div class="col-md-6"> <label class="labels">Create a club</label> {{ form.owner }} <input class="btn" type="submit" value="Add club"> </div> </form> -
How to log a django view
I'm learning to log and I'm not sure what I'm supposed to do with the logger in my view since what I've read around doesn't seem to work or I'm just not understanding something. This are my settings for the logging: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'todo': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), 'propagate': True, }, }, } This is the view and the logging part: from rest_framework import generics, filters from todo import models from .serializers import TaskSerializer from django_filters.rest_framework import DjangoFilterBackend import logging logger = logging.getLogger(__name__) def myview(request): logger.error('Something went wrong') class ListTask(generics.ListCreateAPIView): """ API view to retrieve list of tasks or create new tasks """ queryset = models.Task.objects.all() serializer_class = TaskSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['date'] search_fields = ['description'] class DetailTask(generics.RetrieveDestroyAPIView): """ API view to retrieve or delete a task """ queryset = models.Task.objects.all() serializer_class = TaskSerializer -
How to insert a Django template tag + HTML element in a HTML page with Javascript
How can I safely add a piece of HTML with Django template tags in it using Javascript? For example, if I have something like this in my template: <div id="some-element"> <span id="my-tag">{{ my_data }}</span> </div> <!-- rest of the html page --> If I were to use a script to just edit the innerHTML of the div, like the script below, it'd would just read {{ other-data }} as a string. How can I make it become an actual Django template tag? <script> document.getElementById("some-element").innerHTML = ` <h1>This is may new data {{ other-data }} </h1> {% if value %} <p>This is an if statement</p> {% endif %} ` </script> -
How to Stack Multiple Search Parameters in URL with Django and Ajax
I'm trying to create a filter system on a webpage such that the user can bookmark their searches. The page loads from the basic url: path('foobar/counts', views.foobarCount, name='foobar_counts') This URL loads the proper template on top of the base template and includes everything needed. From there, a series of filters are set up, which send an ajax request to the server. The user can select as many or as few filters as they'd like. The Ajax url is set up as follows: path('foobar/counts/filter', views.foobarCountFilter, name='foobar_count_filter') This all works just fine when the user starts at the foobar/counts URL, but when they want to paste in something like: /foobar/counts/filter?startDate=2001-01-12&endDate=2021-01-12&startComp=2021-01-01&endComp=2021-01-31&assigns... The system properly receives the Ajax request and brings back the proper information, but it does not include the other templates needed to load the webpage. It displays as essentially a plaintext version. Is there a minimally invasive way to retroactively load all the necessary templates when pasting in the search URL? -
How to do ModelName.objects.filter in html
I'm trying to eliminate the amount of code I need to put in my view and want to do this in my html file: {% for committee in c %} {% for article in Article.objects.filter(committee=committee) %} <a class="post-link" href="{% url 'update' id=article.id %}">{{article.title}}</a> {% endfor %} {% endfor %} I am passing my article model and list of c as context in my view. But it gives me this error: TemplateSyntaxError at /admin-dash/ Could not parse the remainder: '(committee=committee)' from 'Article.objects.filter(committee=committee)' Request Method: GET Request URL: http://127.0.0.1:8000/admin-dash/ Django Version: 3.1.3 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '(committee=committee)' from 'Article.objects.filter(committee=committee)' Exception Location: C:\Users\benja\anaconda3\lib\site-packages\django\template\base.py, line 662, in __init__ Python Executable: C:\Users\benja\anaconda3\python.exe Python Version: 3.8.3 Python Path: ['C:\\Users\\benja\\Desktop\\mysite\\mysite', 'C:\\Users\\benja\\anaconda3\\python38.zip', 'C:\\Users\\benja\\anaconda3\\DLLs', 'C:\\Users\\benja\\anaconda3\\lib', 'C:\\Users\\benja\\anaconda3', 'C:\\Users\\benja\\anaconda3\\lib\\site-packages', 'C:\\Users\\benja\\anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\benja\\anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\benja\\anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Tue, 12 Jan 2021 19:41:28 +0000 Error during template rendering In template C:\Users\benja\Desktop\mysite\mysite\blog\templates\admin.html, error at line 18 Could not parse the remainder: '(committee=committee)' from 'Article.objects.filter(committee=committee)' 8 <link rel="stylesheet" href="{% static 'css/admin.css' %}"> 9 <link rel="stylesheet" href="{% static 'css/posts.css' %}"> 10 </head> 11 <main> 12 13 14 <div class="admin-panel"> 15 <div class="posted"> 16 <h1 style='font-size: 7rem; margin-bottom: 20px; margin-top: 0;'>Posts:</h1> 17 {% for committee in c %} 18 {% for article in … -
Enforce or test on_delete behavior of all ForeignKey fields using a specific model
Let's say I have a proxy user model as class UserWithProfile(User): profile_description = models.TextField() class Meta: proxy = True ordering = ('first_name', ) I want to make certain that all data which could in the future be associated with a UserWithProfile entry is deleted when this profile is deleted. In other words I want to guarantee the on_delete behavior of all existing and future ForeignKey fields referencing this model. How would one implement either a test checking this, or raise an error when another on_delete behavior is implemented? I know it would be possible to make a custom ForeignKey class, which is what I will be probably doing, ... class UserWithProfileField(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs.setdefault('to', UserWithProfile) kwargs.setdefault('on_delete', models.CASCADE) super().__init__(*args, **kwargs) ... however that couldn't stop future users from using the ForeignKey class with a different on_delete behavior.