Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Communication of two applications
I need to make an admin panel for the Telegram's bot. I plan to implement the panel itself on Django. What I can use to get Django and the bot to communicate? -
Django ElasticSearch Rest Framework Suggesting Results duplicate title
In my database, there are lots of duplicate titles but their id is not duplicate and other properties are not duplicated. only title duplicate. I have implemented API for auto suggest but it is not currently returning duplicate results. coz, in database, most of the product are duplicate title. the duplicate title is normal but it should not return in API response for auto suggest, this is what I tried: from django_elasticsearch_dsl_drf.filter_backends import ( SuggesterFilterBackend ) from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet from django_elasticsearch_dsl_drf.constants import ( SUGGESTER_COMPLETION, ) class SuggestionsAPIView(DocumentViewSet): document = ProductDocument serializer_class = ProdcutTitleSerializer filter_backends = [ SuggesterFilterBackend, ] suggester_fields = { 'title': { 'field': 'title', 'suggesters': [ SUGGESTER_COMPLETION, ], 'options': { 'size': 20, 'skip_duplicates':True, }, }, } Anyone know about this? How can I get rid of such a duplicate results? -
How to create custom permissions for django admin site
By default when I create a model Django gives permissions like add/change/delete/view If I give any of the above permission to a specific user then that user can view all the objects from that model. But I want to show them only objects linked with foreign keys. Let's Say, I have a Book model class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey( User, on_delete=models.CASCADE ) If I want to give authors permission, they can only view their linked books from the Django admin. How can I do that? -
Cannot run .service file even when its located in /etc/systemd/system
When I try to run the command: systemctl start myportfolio I get the following error message: Failed to start myportfolio.service: Unit myportfolio.service not found. I also checked to see if myportfolio.service was in the right directory and it was: So why wont it run properly? What seems to be the error? myportfolio.service: [Unit] Description=Serve Portfolio Site After=network.target [Service] User=root Group=root WorkingDirectory=/root/team-portfolio ExecStart=/root/team-portfolio/python3-virtualenv/bin/python/root/team-portfolio/python3-virtualenv/bin/flask run --host=0.0.0.0 Restart=always [Install] WantedBy=multi-user.target -
Django Model Instance as Template for Another Model that is populated by Models
I'm trying to create the create a workout tracking application where a user can: Create an instance of an ExerciseTemplate model from a list of available Exercise models. I've created these as models so that the user can create custom Exercises in the future. There is also an ExerciseInstance which is to be used to track and modify the ExerciseTemplate created by the user, or someone else. I'm stripping the models of several unimportant fields for simplicity, but each contains the following: class Exercise(models.Model): # Basic Variables name = models.CharField(max_length=128) description = models.TextField(null=True, blank=True) def __str__(self): return self.name class ExerciseTemplate(models.Model): # Foreign Models workout = models.ForeignKey( 'Workout', on_delete=models.SET_NULL, null=True, blank=True ) exercise = models.ForeignKey( Exercise, on_delete=models.SET_NULL, null=True, blank=True ) recommended_sets = models.PositiveIntegerField(null=True, blank=True) class ExerciseInstance(models.Model): """ Foreign Models """ exercise_template = models.ForeignKey( ExerciseTemplate, on_delete=models.SET_NULL, null=True, blank=True ) workout = models.ForeignKey( 'Workout', on_delete=models.SET_NULL, null=True, blank=True ) """ Fields """ weight = models.PositiveIntegerField(null=True, blank=True) reps = models.PositiveIntegerField(null=True, blank=True) Create a WorkoutInstance from a WorkoutTemplate. The WorkoutTemplate is made up of ExerciseTemplates. But the WorkoutInstance should be able to take the WorkoutTemplate and populate it with ExerciseInstances based on the ExerciseTemplates in the WorkoutTemplate. Here are the models that I have so far: … -
Exposing React App with Local MySQL Database to Internet Using Ngrok
I am very new to ngrok, so please bear with me. I have a very simple React test app that is using Django as a server and local MySQL database. Django pulls/inserts some info from the local database and sends to the frontend. Everything works well. What I'm trying to do is expose this local app to public Internet. I have successfully installed and configured Ngrok, established a tunnel and was able to view the app on a different computer through the address generated by Ngrok. The problem is, I was able to see only the UI that is not related to the database. All data that React pulls from the local database, was not visible when I used a different computer. My question is, is there a way to use the same app through Ngrok and get the same data from the local MySQL database that I see when I just run the app locally? I know that I can create another tunnel that exposes the port MySQL or Django are running on (3306 and 8000 respectively) but if I do this, how would I access the data through Ngrok? Would I need to change anything in React code? … -
Django - Passing an extra argument from template to urls.py to class-based view
Basically, I would like to transition from a page showing a table (which is the result of a user query), to a page where the user can edit an entry in the table (this page is built using UpdateView), and then straight back to the previous page but this time showing the table with the new update reflected. There are other posts on similar situations but none seem to show how to implement this using a class-based view, so any advice here would be most appreciated. So far I have come up with the approach below. Here, I am trying to pass a parameter holding the URL of the table page, from the template for the table page to urls.py and then onto the view. However, I don't think I am using the correct syntax in urls.py as the value of the previous_url parameter in the view is simply "previous_url". Link in the template for the table page <a href="{% url 'entry_detail' item.pk %}?previous_url={{ request.get_full_path|urlencode }}">Edit</a> URL path('entry/<int:pk>/edit/', EntryUpdateView.as_view(previous_url="previous_url"), name='entry_update'), View class EntryUpdateView(LoginRequiredMixin, UpdateView): model = Entry template_name = 'entry_update.html' fields = ('source', 'target', 'glossary', 'notes') previous_url = "" def form_valid(self, form): obj = form.save(commit=False) obj.updated_by = self.request.user obj.save() return … -
django.core.exceptions.ImproperlyConfigured: Cannot import 'mainApp'. Check that 'apps.mainApp.apps.MainappConfig.name' is correct
I have cloned this project from github and their were some modules which i needed to install which are their in the "requirements.txt" file. Earlier I was getting the errors while installing this file as well. Later i updated the versions of some module and this file run but It started backtracking and it continued for almost 12 hours then i cancelled it. And after running the manage.py filecode, it shows the following error: C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\__init__.py:102: RequestsDependencyWarning: urllib3 (1.26.4) or chardet (5.0.0)/charset_normalizer (2.0.12) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported " C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\__init__.py:102: RequestsDependencyWarning: urllib3 (1.26.4) or chardet (5.0.0)/charset_normalizer (2.0.12) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported " Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\config.py", line 245, in create app_module = import_module(app_name) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mainApp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\threading.py", line … -
Different between template_name and template_name_field?
class ArticleDetailView(DetailView): template_name = None template_name_field = None 1)Why template_name_field default value is None? 2)template_name vs template_name_field -
Python virtual environment does not have a scripts folder and cannot be activate
I am new at programming and I want to work with Python and meanwhile with the Django Framework. For installing a venv I use "python3 -m venv ./venv/drf" and insert this in a terminal in VS code. I found this on my research about my problem. But when I installed the venv there is not a script folder in the venv folder. For activating my venv I tried "source .venv/drf/bin/activate" but this is neither working. I am working on a mac and I installed Python previously. I even installed Django on VS code. What can I do to implement the scripts folder and activate my venv? -
How Can I Verify that Django @cached_property is Cached?
In the below example, I have questions. Example from django.utils.functional import cached_property class Product(models.Model): class ProductType(models.TextChoices): PRODUCT = 'PRODUCT', _('Product') LISTING = 'LISTING', _('Listing') my_model = models.ForeignKey(MyModel, on_delete=models.CASCADE, related_name='products') product_type = models.CharField(max_length=7, choices=ProductType.choices) class MyModel(models.Model): ... @cached_property def listing(self): return self.products.get(product_type=Product.ProductType.LISTING) Questions Is the listing property being cached on the MyModel object? I ask because it's accessing .get() of a queryset which has greater implications. Ex: instance = MyModel() instance.listing # hits db instance.listing # gets from cache? How can I set up a scenario to inspect and verify that caching of instance.listing is in-fact happening? I read to look in the __dict__ method of instance.listing.__dict__ but I don't notice anything specific. -
expanding dict model field in django
I need a way to be able to enter an unspecified number of arbitrary, integer values with an auto-incrementing key into a dictionary in a django model. It would need to look, or at least function, like this: { "1":6, "2":10, "3":0, ... "n":42 } I'm hoping there will be a simple solution like: class Foo(models.Model): title = models.CharField(max_length=100) dictOfInts = { models.AutoField(): models.IntegerField, models.AutoField(): models.IntegerField, models.AutoField(): models.IntegerField ... # it would start with just one and automatically add more k-v pairs as nessary } #other fields ect def __str__(self): return self.title Unfortunately, I know that doesn't work and wouldn't function how the comment suggests, but it would need to act like that for the end-user. I've looked through the docs and the only workaround I found there was using models.JSONField(), but that requires you to type out the dict yourself, which is not ideal. Another possible way that I found would be to separate the dict and the k-v pairs, linking them with a foreign key, but I couldn't quite figure out how to integrate it and it seemed very messy even if I could. If you need any more info, just let me know. Any help is much … -
Unable to push json file to Heroku for database data dump
I'm working on a school project, I have no experience with any of this and am having a hard time with this last step of setting up a website. For some background, the front end is coded in Next.js, backend is Python utilizing Django, and I have deployed the backend to Heroku (I have the app built and the database (postgreSQL) setup). I have done all of this following a tutorial that I found on Udemy which is only about a year old. I have run into some issues along the way but was able to figure them out after some trial and error, but this one is really giving me a hard time. So, in the tutorial he does a datadump and puts it into a file named "dump.json", then he runs the following command: heroku run python manage.py loaddata dump.json, which dumps the data into Heroku and the database populates and his Heroku app is up and running (it's connected to the Django rest framework, which is coded in the front end). Well, here is what I get when I run the command, I have to specify the path to manage.py otherwise it won't work, fyi... I have … -
django "no such table" when adding database entries via terminal
I am trying to create a relational database (one to many) in my models.py file. But when trying to add entries into my database i get an error saying: django.db.utils.OperationalError: no such table: app1_prices. I have ran makemigrations and migrate in the terminal as well, so that must not be the problem models.py from django.db import models class Figure(models.Model): id = models.CharField(max_length=12, primary_key=True) pieces = models.IntegerField() def __str__(self): return self.id class Prices(models.Model): id = models.ForeignKey(Figure, on_delete=models.CASCADE, primary_key=True) price_new = models.DecimalField(decimal_places=2, max_digits=8) price_used = models.DecimalField(decimal_places=2, max_digits=8) date = models.DateField(blank=True, null=True) def __str__(self): return self.id, self.date 0001_initial.py from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Figure', fields=[ ('id', models.CharField(max_length=12, primary_key=True, serialize=False)), ('pieces', models.IntegerField()), ], ), migrations.CreateModel( name='Prices', fields=[ ('id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='app1.figure')), ('price_new', models.DecimalField(decimal_places=2, max_digits=8)), ('price_used', models.DecimalField(decimal_places=2, max_digits=8)), ('date', models.DateField(blank=True, null=True)), ], ), ] The code i have tried inside the terminal: >>> from app1.models import Figure, Prices >>> f1 = Figure("sw0001a", 5) >>> f1.save() >>> p1 = Prices(f1.id, 2.00, 1.20, "2022-05-03") >>> p1.save() django.db.utils.OperationalError: no such table: app1_prices -
Increasing the searching speed of Django set.all()
I am using Django to filter through a MongoDB full of data. Right now I have code that is working and have found where my slowdown is at... def does_this_property_apply(prop, app, dev, event): for platform_device in prop.platformdevice_set.all(): for event in platform_device.applicable_events.all(): if event.name == event: for app in platform_device.applicable_app.all(): if app.name == app: for device in platform_device.applicable_device.all(): if device.name == dev: print("This property applies") Basically I have 400+ properties that have a bunch of metadata. Inside of each property is a platform_device object (model) that contains information such as app, dev, and event. Think of it as this property only applies to certain applications, on certain devices, on certain user actions (events). Each property can have multiple of these. I am new to Django and trying to find out how I could quickly search all platform_device in the database and find if this property (prop) is applicable to my event, device, and application. class PlatformDevice(models.Model): _id = models.UUIDField(unique=True, primary_key=True,default=uuid.uuid4, editable=False) name = 'Property Specifics' property_field = models.ForeignKey('Property', on_delete=models.CASCADE) applicable_app = models.ArrayReferenceField(to=Platform, on_delete=models.CASCADE, blank=True) applicable_device = models.ArrayReferenceField(to=Device, on_delete=models.CASCADE, blank=True) applicable_events = models.ArrayReferenceField(to=Event, on_delete=models.CASCADE, blank=True) event_group = models.ArrayReferenceField(to=EventGroups, on_delete=models.CASCADE, blank=True) def __str__(self): return self.name -
comments display wrong when delete/edit button is removed due to authentication
My comment section is acting fine when am the user who typed the comments and have permission to see the edit delete button. Like in picture below: But when i enter on a user who dident post any of the comments and the delete and edit button dosent show its a mess picture below: Its wierd how do i fix it so the none owner of the comment that dosent see the edit/delete button sees the feild the same just excluded the delete/edit button? Would really appreciate some help product_detail.html The code starts at the bottom of the template under Reviews {% extends "base.html" %} {% load static %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} {% block content %} <div class="overlay"></div> <div class="container-fluid"> <div class="row"> <div class="col-12 col-md-6 col-lg-4 offset-lg-2"> <div class="image-container my-5"> {% if product.image %} <a href="{{ product.image.url }}" target="_blank"> <img class="card-img-top img-fluid" src="{{ product.image.url }}" alt="{{ product.name }}"> </a> {% else %} <a href=""> <img class="card-img-top img-fluid" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}"> </a> {% endif %} </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="product-details-container mb-5 mt-md-5"> <p class="mb-0">{{ product.name }}</p> <p class="lead mb-0 text-left font-weight-bold">${{ product.price … -
django-formset package use in class base view
when I use this package (django-formset 0.8.8) from "FormCollections" class after submit form redirect to success URL but the data doesn't saved in database this model is for quiz data for every device model.py from django.db import models from device.models import Device class QuestionTraining(models.Model): ANSWER_CHOICES = ( ('1', 'گزینه 1'), ('2', 'گزینه 2'), ('3', 'گزینه 3'), ('4', 'گزینه 4'), ) device = models.ForeignKey( Device, on_delete=models.CASCADE, verbose_name='دستگاه') question = models.CharField(max_length=500, null=True) op1 = models.CharField(max_length=200, null=True) op2 = models.CharField(max_length=200, null=True) op3 = models.CharField(max_length=200, null=True) op4 = models.CharField(max_length=200, null=True) answer = models.CharField(max_length=1, choices=ANSWER_CHOICES, null=True) def __str__(self): return self.question I use this form to show inline formset for each quiz forms.py from django import forms from .models import QuestionTraining class CreateQuestionTrainingDeviceForm(forms.ModelForm): class Meta: model = QuestionTraining fields = ['device'] class CreateQuestionTrainingForm(forms.ModelForm): class Meta: model = QuestionTraining fields = ['question', 'op1', 'op2', 'op3', 'op4', 'answer'] class PhoneNumberForm(forms.Form): phone_number = forms.fields.CharField() label = forms.fields.CharField() class QuestionCollection(FormCollection): min_siblings = 1 max_siblings = 5 extra_siblings = 1 question = CreateQuestionTrainingForm() class ContactCollection(FormCollection): divice = CreateQuestionTrainingDeviceForm() question = QuestionCollection() after submitting form, the data doesn't save in database, but redirect to success URL views.py class QuestionTrainingCreateView(FormCollectionView): template_name = 'question_training/create.html' collection_class = ContactCollection success_url = '/question_training/list' -
Django objects cannot be access from outside the shell
I'm going to assume this is a settings issue, but I just can't seem to figure it out. This is my views.py file from django.shortcuts import render from blogPost.models import blogpost def index(request): blog_list = blogpost.objects.all() context = {'blog_list': blog_list} print(context) return render(request, "index.html",context) When I run the server, I get this error Internal Server Error: /blogPost/ Traceback (most recent call last): File "C:\Users\Jonny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Jonny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Jonny\Dropbox\Projects\django_app\meme_django_app\meme_django_app\blogPost\views.py", line 5, in index blog_list = blogpost.objects.all() AttributeError: 'function' object has no attribute 'objects' I know that blogpost does have objects because when I run the same command within the shell I get an output In [1]: from blogPost.models import blogpost In [2]: blogpost.objects.all() Out[2]: <QuerySet [<blogpost: blogpost object (1)>, <blogpost: blogpost object (2)>]> Why isn't my object accessible in my .py file, but it is in the shell? -
Get User model data in drf-social-oauth2 response after login
So I am using drf-social-oauth2 for authentication and React in the frontend, const handleGoogleLogin = (response) => { setLoading(true); axios .post(`${apiBaseURL}/auth/convert-token`, { token: response.accessToken, backend: "google-oauth2", grant_type: "convert_token", client_id: drfClientId, client_secret: drfClientSecret, }) .then((res) => { const { access_token, refresh_token } = res.data; const cookies = new Cookies(); cookies.remove("google_access_token"); cookies.remove("google_refresh_token"); cookies.set("google_access_token", access_token, {path: "/", maxAge: 24*60*60}); cookies.set("google_refresh_token", refresh_token, {path: "/", maxAge: 24*60*60}); setLoading(false); console.log(res); console.log(res.data); // window.location.href = `${appBaseURL}/`; }) .catch((err) => { setLoading(false); createErrorNotification(); }); }; Here the login is successful and everything works fine, however the response I get is just {access_token: 't3LqiUvz0x4HBWGDsSyLP7fsyKejJf', expires_in: 63583.018772, scope: 'read write', refresh_token: 'GEkGz8teGATlYY0pQ1zuntN8ODfFT4', token_type: 'Bearer'} What can I do to have all the user info like his model fields in the response? Couldn't find anything related to this anywhere -
Django admin models only showing quantity
I have been trying to find answers on some related questions, but not successful. I've created models and registered in the admin.py, all models are showing except Category models. I have tried expanding and collapsing it. It only flashes the 5 categories and then shows only quantity. I would really appreciate your assistance Image : Only quantity shows instead of the actual 5 categories Models.py class CategoryAdmin(admin.ModelAdmin): list_display = ['title', 'parent', 'status'] list_filter = ['status'] class Category(MPTTModel): STATUS = ( ('True', 'True'), ('False', 'False'), ) parent = TreeForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=30) keyword = models.CharField(max_length=255) description = models.CharField(max_length=255) image = models.ImageField(blank=True, upload_to='images/') status = models.CharField(max_length=10, choices=STATUS) slug = models.SlugField() create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) class MPTTMeta: order_insertion_by = ['title'] def __str__(self): return self.title Admin.py class CategoryAdmin2(DraggableMPTTAdmin): mptt_indent_field = "title" list_display = ('tree_actions', 'indented_title', 'related_products_count', 'related_products_cumulative_count') list_display_links = ('indented_title',) def get_queryset(self, request): qs = super().get_queryset(request) # Add cumulative product count qs = Category.objects.add_related_count( qs, Product, 'category', 'products_cumulative_count', cumulative=True) # Add non cumulative product count qs = Category.objects.add_related_count(qs, Product, 'category', 'products_count', cumulative=False) return qs def related_products_count(self, instance): return instance.products_count related_products_count.short_description = 'Related products (for this specific category)' def related_products_cumulative_count(self, instance): return instance.products_cumulative_count related_products_cumulative_count.short_description = 'Related products (in tree)' … -
When trying to use a rq worker get rq.exceptions.DeserializationError
When trying to run django-rq worker I keep getting this error 15:35:26 Traceback (most recent call last): File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/job.py", line 249, in _deserialize_data self._func_name, self._instance, self._args, self._kwargs = self.serializer.loads(self.data) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/db/models/base.py", line 2141, in model_unpickle model = apps.get_model(*model_id) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/apps/registry.py", line 199, in get_model self.check_models_ready() File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/apps/registry.py", line 141, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/worker.py", line 1026, in perform_job self.prepare_job_execution(job) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/worker.py", line 911, in prepare_job_execution self.procline(msg.format(job.func_name, job.origin, time.time())) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/job.py", line 284, in func_name self._deserialize_data() File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/job.py", line 252, in _deserialize_data raise DeserializationError() from e rq.exceptions.DeserializationError Traceback (most recent call last): File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/job.py", line 249, in _deserialize_data self._func_name, self._instance, self._args, self._kwargs = self.serializer.loads(self.data) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/db/models/base.py", line 2141, in model_unpickle model = apps.get_model(*model_id) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/apps/registry.py", line 199, in get_model self.check_models_ready() File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/apps/registry.py", line 141, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/worker.py", line 1026, in perform_job self.prepare_job_execution(job) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/worker.py", line 911, in prepare_job_execution self.procline(msg.format(job.func_name, job.origin, time.time())) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/job.py", line 284, in func_name self._deserialize_data() File … -
Not saving a user to a group
I have this model in the admin panel. when I create this user from the admin panel, he simply is not added to the group. if I also try to add a user to the group through the shell, it works, but in the code is when creating (looked through the debugger) it returns None and does not add the user to the group. @admin.register(ProxyMechanicUser) class Mechanic(admin.ModelAdmin): list_display = ('username', 'phone_number', 'last_login', 'is_active') fields = ('username', 'password', 'is_staff', 'is_active', 'first_name', 'last_name', 'email', 'phone_number', 'groups','date_joined') readonly_fields = ('date_joined', 'last_login') def save_model(self, request: HttpRequest, obj, form, change): password = form.cleaned_data['password'] obj.password = make_password(password=password) obj.save() group = Group.objects.get(name=MECHANIC) obj.groups.add(group) # return None and dont setup user in groups # group.user_set.add(obj) its too dont work. return super(Mechanic, self).save_model(request, obj, form, change) -
Double post after refresh django
After i posted my comment and deside to refresh the page it adds the same comment over and over on every refresh how can i stop this? The code for the comment review is at the far bottom in the template.html. And the review code is under "def product_detail" in the views.py Hope someone can give me some tips so if i refresh it dosent do another post. template {% extends "base.html" %} {% load static %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} {% block content %} <div class="overlay"></div> <div class="container-fluid"> <div class="row"> <div class="col-12 col-md-6 col-lg-4 offset-lg-2"> <div class="image-container my-5"> {% if product.image %} <a href="{{ product.image.url }}" target="_blank"> <img class="card-img-top img-fluid" src="{{ product.image.url }}" alt="{{ product.name }}"> </a> {% else %} <a href=""> <img class="card-img-top img-fluid" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}"> </a> {% endif %} </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="product-details-container mb-5 mt-md-5"> <p class="mb-0">{{ product.name }}</p> <p class="lead mb-0 text-left font-weight-bold">${{ product.price }}</p> {% if product.category %} <p class="small mt-1 mb-0"> <a class="text-muted" href="{% url 'products' %}?category={{ product.category.name }}"> <i class="fas fa-tag mr-1"></i>{{ product.category.friendly_name }} </a> </p> {% endif %} {% if product.get_rating > … -
Django can't load images nor files to neither media nor admin
I'm trying to learn Django but I'm struggling to make a form using crispy forms to load some user info, file and image. I can load info just fine and display it in admin but I'm struggling to do the same for files for Images and Files, aka image and resume fields. The forms shows just fine but just won't take input for both images and files. Please tell me If I have to provide more detail, any help is appreciated thanks. Models.py class Application(models.Model): id = models.AutoField(primary_key=True) jobpost = models.ForeignKey(JobPost, on_delete=models.CASCADE, editable=False, related_name='post', blank=True, null=True) applicant = models.ForeignKey(User, editable=False, on_delete=models.CASCADE, related_name='recruits') Firstname = models.CharField(max_length=200, default="") Lastname = models.CharField(max_length=200, default="") Cin = models.CharField(max_length=200, default="") Telephone = models.IntegerField(default=212) Email = models.EmailField(max_length=200, default="") displaypic = models.ImageField(upload_to='images/', null=True, blank=True, default='images/default.png') resume = models.FileField(upload_to='resume/', null=True, blank=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) date_applied = models.DateTimeField(auto_now=False, auto_now_add=True) archived = models.BooleanField(default=False, editable=False) def __str__(self): return self.applicant.username class Meta: ordering = ["-date_applied", "-updated"] views.py (please only see if 'applyjob' clause) @login_required def detailjob(request, job_id): title = 'Jobs' profile = Profile.objects.get(user=request.user) job = JobPost.objects.get(id=job_id) posts = JobPost.objects.exclude(id=job_id) if request.method=='POST': if 'applyjob' in request.POST: form = ApplicationForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.jobpost = job instance.applicant = request.user instance.save() return … -
Django package / solution: web app for data collection and management
We are in need of creating an app using python which will be mainly used for data collection or data entry relatively wrt accounting. Need the solution to display records in table grid allows user to add, edit, delete, search, print etc.. the records. Kindly suggest the best frame work for the same. I'm though trying to learn Django. Wondering if that'll suffice the needs.