Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Django not able to match URL with trailing slash?
I'm using using the Django rest framework. I'm using Postman with query parameters in the URL. http://localhost:9090/api/payment_management/?cutoffDate=2022-08-05T00:00:00.000Z and my urls.py # this is a child of "/api", using include in the root urls.py urlpatterns += [path('payment_management/', get_cutoff)] I explicitly put a trailing slash at the end of the url. But I get the following from the shell Not Found: /api/payment_management/ [08/Aug/2022 18:33:32] "GET /api/payment_management/?cutoffDate=2022-08-08T00:00:00.000Z HTTP/1.1" 404 I literally put a trailing slash and it's giving me an error. Am I missing something here? APPEND_SLASH is set to true in the settings. -
I need to filter the end points in swagger ui drf. How can i do in Django
I need to customize the swagger ui like filter. Which means if user login the user can see only particular end points. Now I am getting all the end points on my project. Every user can see all end points. How can I achieve that. -
MySQL database breaks while running too many tests in django
I have a Django project with hundreds of tests and after adding about 50 more tests, when I run all of the tests at once using python manage.py test, almost all of the tests raise the following error: Traceback (most recent call last): File ".../venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor.execute(sql, params) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 79, in _execute self.db.validate_no_broken_transaction() File ".../venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 437, in validate_no_broken_transaction raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. During handling of the above exception, another exception occurred: File ".../venv/lib/python3.9/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 653, in first for obj in (self if self.ordered else self.order_by('pk'))[:1]: File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File ".../venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1145, in execute_sql cursor.close() File ".../venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 83, in close while self.nextset(): File ".../venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 137, in nextset nr = db.next_result() MySQLdb._exceptions.OperationalError: (2006, '') But if I run the tests individually, … -
How do you launch a Tkinter application from a django website
I created a Django website and I want to launch a tkinter program if the user clicks on a button. Can anyone tell me how to do that? Any help is appreciated. -
Getting 504 Gateway Time-out nginx/1.18.0 (Ubuntu) in django nginx
I am facing problems launching my django app in digitalocean. I have done all the needful but I am quite sure I made error some where. Below is my nginx configuration file. What could be the problem . Thanks alot . PLease I would also love to know how to access nginx error log file through command line. server { server_name server_Ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/myproject/smsdigo; } location /media/ { root /home/username/myproject/smsdigo; } location /locale/ { root /home/ebong/myproject/smsdigo; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } server { listen 80; client_max_body_size 3000M; client_body_buffer_size 3000M; client_body_timeout 120; } -
Run task from other Task
I try run task send_request from task start_distribution with apply_async method not work. from celery import shared_task, group from celery.utils.log import get_task_logger from .models import Distribution, Client logger = get_task_logger(__name__) @shared_task(bind=True, max_retries=200, default_retry_delay=30) def send_request(self, distribution_id, client_id): pass @shared_task(bind=True) def start_distribution(self, distribution_id): distribution = Distribution.objects.get(pk=distribution_id) logger.info(f'distribution obj:') logger.info(f' pk: {distribution.pk}') logger.info(f' start date: {distribution.start_date}') logger.info(f' end date: {distribution.end_date}') logger.info(f' tag: {distribution.tag.name}') logger.info(f' mobile_code : {distribution.mobile_code.mobile_code}') logger.info(f' body message : {distribution.body_message}') clients_for_send = Client.objects.filter( mobile_code=distribution.mobile_code, tag=distribution.tag ).all() logger.info('Pk sending client:') [logger.info(client.pk) for client in clients_for_send] g = group(send_request.s(distribution_id, client.pk) for client in clients_for_send) g.apply_async( queue='external_req', expires=distribution.end_date ) -
Django and JS for loop: how to change a variable value into {%static 'path' %}?
I'm trying to find out how to change a path in a picture having JS logic in the Django template. As an example - according to logic in the JS script - change from: hangman_game/img/s0.jpg to hangman_game/img/s1.jpg then to hangman_game/img/s2.jpg ect In the previous framework, it was working. But now, I'm migrating a page to the Django framework. Almost all are ready, but JS for loop syntax mentioned previously isn't working and I'm looking for a way: how to properly set a for loop that will generate a new path to the picture in the HTML file. in my html file I have: <div id="gallows"> <img src="{% static 'hangman_game/img/s0.jpg' %}" alt="" /> </div> This part is ok. The problem is, that this div is linked to for loop in js file where I previously had: var errorCount = 0; if(matched == true) { // errorCount for changing picture: errorCount++; var picture = "img/s" + errorCount + ".jpg" document.getElementById("gallows").innerHTML = '<img src="'+picture+'"alt="" />'; Outside Django, it was working, but after migrating to Django it stopped (obviously). Because JS var picture is a string, I'm pretty sure that I can use {% static %}, but I don't know how. I tried to … -
Testing django migration with sqlite django.db.utils.NotSupportedError
I am upgrading a django project. And I need to run tests. There is a test for the migration of a database scheme, but I receive an error: "django.db.utils.NotSupportedError: SQLite schema editor cannot be used while foreign key constraint checks are enabled. Make sure to disable them before entering a transaction.atomic() context because SQLite does not support disabling them in the middle of a multi-statement transaction." Not only is this error message really long, but I also have no idea left how to fix it. I already tried turning of foreign key checks using PRAGMA foreign_keys = 0;. Is this the right approach? Please help me I am stuck here for days now. executor = db.migrations.executor.MigrationExecutor(db.connection) old_apps = executor.loader.project_state(self.migrate_from).apps executor.migrate(self.migrate) # this line fails This code is run before atomics = {} for db_name in cls._databases_names(): atomic = transaction.atomic(using=db_name) atomic._from_testcase = True atomic.__enter__() atomics[db_name] = atomic return atomics Is there anything I misunderstood? -
Django create user command issue while trying to add a new user through a html form
I have successfully created a table in the database and can add data from the admin panel onto the table but when i used the form displayed on a url by clicking submit a new user is not created. view.py from django.shortcuts import render, redirect from formRegister.models import FormRegister Create your views here. def register(request): if request.method == 'post': first_name = request.POST['fisrt_name'] last_name = request.POST['last_name'] username = request.POST['username'] user = FormRegister.objects.create_user(username=username, first_name=first_name, last_name=last_name) user.save(commit = True); return redirect('/') else: return render (request, 'formRegister.html') -
filter method in try block is not working in django
I have a model called properties which contains product details with the respective user IDs. The user id is called uid in the model. I wrote a function in views.py to get the products that are only posted by logged-in user. I use the filter method in it, but it's not working. How can I solve this? def view_products(request): try: user = request.user.id c = properties.objects.filter(uid=user,status=True) return render(request,'view_products.html',{'c':c}) except: txt = """<script>alert('You have no properties to view...');window.location='/userhome/';</script>""" return HttpResponse(txt)``` -
How can I send a post request in Django Rest Framework where a key has list of json objects?
I am new to Django Rest Framework and django itself. I want to post a request wherein a key has a list of objects. So far, I have created the User_parameter model and I am passing it as a foreign key. I am lost and do not know what to do from here on. Do I need to override create() in the User_Parameters_Serializerserializer or something entirely different? I have added code for my models.py, serializer.py, the function-based view where I am handling the post request and my desired post request outline. Thank you for your time. I really appreciate it. # The post request I want to send looks like this: { "model_path": "some path", "data_path": "some path for csv", "sep": ",", "target_column": "target_column", "label_column": "lable_column", "function_names": "some strings", "user_params": [{ "standard_deviation": between[1-3], "direction": 0 OR 1, "feature_list": "some strings" }] } #models.py class User_Parameters(models.Model): def validate_standard_deviation_number(value): if value not in range(1,4): raise ValidationError( _('%(value)s is not in range: [1-3]'), params={'standard deviation': value}, ) def validate_direction(value): #### 0 - Negative #### 1 - Positive if value not in range(0,2): raise ValidationError( _('%(value)s needs to be either 0 (Negative) or 1 (Positive)'), params={'direction': value}, ) standard_deviation = models.IntegerField(default=1, validators=[validate_standard_deviation_number]) direction = … -
What's an efficient way of synchronizing git pull requests and restarting systemctl services for multiple Django-Q clusters?
I'm running numerous Django-Q clusters (on Ubuntu focal) to perform distributed computing on large data sets. I have production clusters and development clusters that each have their own git branch. I need a way to synchronize the updating and restarting of these cluster systemctl services when changes to their respective git repositories are made. Currently I ssh into each machine and run the following commands. $ git pull $ sudo systemctl restart qcluster I appreciate any ideas you may have. -
adding more then one data in Many to many in Django
I have a project I want to add() more then one data to ManyToMany field class Product(models.Model): name = models.models.CharField(Name) class Tags(models.Model): product_of_names = models.ForeignKey(Product) tag_name = models.models.CharField() class Group(models.Model): tag_group = models.ManyToManyField(Tags) views.py def home(request, pk): product_name = Product.objects.get(pk=pk) tag = Tags.objects.filter(product_of_names=product_name) print(tag.id) >>> 1 >>> 2 >>> 3 insert_data = Group.objects.create() insert_data.tag_group.add(tag) insert_data.save() it add just one I want to add them all in ManyToMany Thanks for any help -
Copy Django Model Input into another Django Database
I am trying to figure out if there was a way that once I uploaded something to one of my Django database files, that, that same upload would also upload to another database file, so if I go to delete one of them, it is saved in the other. class CompanyInfo(models.Model): company_name = models.CharField("Company Name", unique=True, max_length=50, default="") # Identifiers identifier = models.IntegerField(default=0) # Company Information sector = models.CharField("Sector", max_length=50,default="") location = models.CharField("Location", max_length=100, default="") year_founded = models.IntegerField("Year Founded", default=2000) company_description = models.TextField("Company Description", default="") state_registered_in = models.CharField("State of Registration", choices=states_list, max_length=2, default=2) company_url = models.URLField("Company URL", max_length=200, default="", blank=True, null=True) phone_number = models.CharField("Phone Number", max_length=20,default="") company_logo_url = models.ImageField("Company Logo", upload_to=None, height_field=None, width_field=None, max_length=100, blank=True, null=True) facebook = models.URLField("Facebook URL", max_length=200, default="", blank=True, null=True) linkedin = models.URLField("Linkedin URL", max_length=200, default="", blank=True, null=True) instagram = models.URLField("Instagram URL", max_length=200, default="", blank=True, null=True) email = models.EmailField("Email Address", max_length=40,default="") def __str__(self): return "{} from {}".format(self.company_name, self.location) Basically, once these values are created for the "CompanyInfo" class, I want it to also upload itself into another Django class in the exact same way, so if I eventually delete the input in the "CompanyInfo" class, there will still be a saved version in the other created … -
Best practice for Django inline images in TextField?
I have a portfolio site that I am building, and I will be porting a bunch of posts from my GitHub sites, all in Markdown. Thankfully, I have Markdown, and LaText math is working great on the site. However, I can not get images working in the blog body, which is a TextField. I have images working elsewhere on the site. I am looking at django-tinymce and django-inline-media as possible solutions. Any thoughts on these or other alternatives? This is what I have tried in my body so far, with many variations on the path to the image: ### MD  ### HTML <img src= {{ "images/my_image.jpg" }} alt="My image"> With the following turned on in urls.py. from django.contrib.staticfiles.urls import staticfiles_urlpatterns ... urlpatterns += staticfiles_urlpatterns() ### Static <img src="{% static "images/my_image.jpg" %}" alt="My image" /> -
retrieve the value of the variable sent to my detail view (class based view) in get_context data to do a conditional test
I would like to know how to retrieve the value of the variable sent to my detail view in get_context data to do a conditional test and display the result of test and the value send by context_object_name in the models i just have a list of words class Palind(models.Model): mot = models.CharField(max_length=200) def __str__(self): return self.mot the views class PalindDetailView(DetailView): model = Palind context_object_name = "palind" template_name = "pages/palind_detail.html" def get_context_data(self, **kwargs): m = "" # here i need get value of variable send in my detail view context = super(PalindDetailView, self).get_context_data(**kwargs) if m.startswith("k"): test = "ok" else: test = "not ok" context['test'] = test return context in my urls.py path("<int:pk>/", PalindDetailView.as_view(),name="palind_detail") in template <p> {{ palind.mot }} {{ test }} </p> thank you for all info -
How to go building customer user Token authentication in DRF?
I am trying to do user Token authentication using DRF and I have done that succesfully, but for default USER Model of django , I am want to properly configure the fields in that like I dont want username and wanna make email & password for login and wanna add more fields like first_name and last_name during signup process. I want to add one more field which will say whether this is a student or teacher or a superuser. during signup the data will get stored accordingly. I am messed up with this form past 3 days, and currently exhausted, kindly help me in mitigating this issue. -
Yet another question why django can't see the app
I want all the apps to be in the same shared apps folder. But django settings doesn't want to see the created app. how I created the app Created an empty apps folder in the project root directory. Created an empty __init__.py file in it Created an empty folder inside apps folder - creative_performer Run the command python manage.py startapp creative_performer apps/creative_performer Got the following structure /gpanel /projects urls.py settings.py .... /apps __init__.py /creative_performer /migrations __init__.py apps.py models.py .... manage.py settings.py PROJECT_APPS = ['creative_performer'] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] + PROJECT_APPS But after server run got 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 'creative_performer' I have also tried creating an app with the command django-admin startapp creative_performer Same result If create an app in the root of the project, without using the apps shared folder, everything starts working -
django gettext windows binary installer
I have installed the gettext binaries on windows from here (the upper one): Referenced by Django Docs - mlocati My setup was successful, but when I try to run: django-admin makemessages -l de to create a .po file for german translations, CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. I am a little bit confused, because the download seemed to be okay, but probably sb faced a similar issue? Or can anybody give me an advice here? -
django permissions not being added to groups
I have created a project with x apps. My aim is to create groups with permissions attached to them that populate auth tables - 'auth_groups' 'auth_permissions' and 'auth_group_permissions' on initial migration & migrate Installed apps is up to date, tried with app name,i.e "morgue' and "morgue.apps.MorgueConfig" - used terminal to check apps in apps class. database: tried in both mysql and sqlite3 Problem: I am just trying to attach the default django perms to groups. Problem is some of the groups & permissions combo works whilst others will not add permissions to group. I have 10 groups 6 will do as required four will not. ~ see my code below for how i have attempted todo this. my code: from django.contrib.auth.management import create_permissions from django.contrib.auth.models import Group, Permission from django.db import migrations class Populator(object): def populate_groups(apps, schema_editor): # Create user groups user_roles = [ "Admin only", "Morgue only", ] for name in user_roles: Group.objects.create(name=name) for app_config in apps.get_app_configs(): app_config.models_module = True create_permissions(app_config, verbosity=0) app_config.models_module = None all_perms = Permission.objects.all() - does return all permissions # morgue - 'i substituted for permission.content_type.app_label, does exist in database' morgue_perms = [i for i in all_perms if i.content_type.app_label == "morgue"] # group is created … -
Upload Image in Django with Ajax
This question is asked many times. And after long time trying I gave up. I try to upload an image to the server with an Ajax function. The Ajax function does submit quite a lot of data (I deleted the unnecessary part). The console.log gives me an empty array. What is wrong with my function? Here is the HTML: <form method="POST" id="form-create" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="myImg" name="myImg"> </form> This is the script $(document).on('submit', '#form-create', function (e) { e.preventDefault() var formData = new FormData(); formData.append('myIMG', $('#myIMG')[0]); console.log(formData) $.ajax({ type: 'POST', cache: false, url: "{% url 'creator:build' %}", data: { img:formData, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success: function (data){ if (data.msg === "Success") { $('h4').html('It worked!'); } if (data.msg === 'Fail') { $('h6').html('Sorry! There was a problem...'); } }, }); }); -
React Django Stripe Button
I have a react frontend and a Django/DRF backend. I am trying to create a button on the frontend that allows users to purchase a product via stripe. The below react code works fine for purchasing item. However, it does not register the purchase under specific user, meaning that you can purchase an item, but it is not linked to any user because it does not have the token (identifying the user who is making the purchase). return ( <section> <div className='product'> <img src='https://i.imgur.com/EHyR2nP.png' alt='The cover of Stubborn Attachments' /> <div className='description'> <h3>Stubborn Attachments</h3> <h5>$20.00</h5> </div> </div> <form action={`${API_URL}/api/stripe/create-checkout-session`} method='POST' > <button className='button' type='submit'> Checkout </button> </form> </section> ); }; Here is what I tried: const Playsub = () => { const purchase_item = () => async dispatch => { if (localStorage.getItem('access')) { const config = { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${localStorage.getItem('access')}`, 'Accept': 'application/json' } }; const body = JSON.stringify({ token: localStorage.getItem('access') }); const res = await axios.post(`${API_URL}/api/stripe/create-checkout-session`, body, config) .then((res) => { console.log(res.data) }) .catch(err => { console.log(err.response.data) }); }}}; return ( <section> <form> <button onClick={purchase_item} className='button' type='submit'> Checkout </button> </form> </section> ); }; export default Playsub; The above code when clicking on the button created gives … -
How to send a message by time in a datatimefield in DJANGO?
Hello everyone I am making a REST application based on Django Rest. I have a mailing model and fields with the start date and the end date of the mailing. I would like the newsletter to be sent by the value in the creation date field and completed in the end date field. I am a beginner, and I have no ideas about implementing such an idea. Could it be Celery? class MailingList(models.Model): start_dt = models.DateTimeField() text = models.TextField(max_length=500) operator_code = models.ForeignKey( OperatorCode, related_name='+', on_delete=models.CASCADE, ) tag = models.ForeignKey( Tag, related_name='+', on_delete=models.CASCADE, ) end_dt = models.DateTimeField() -
Adding custom table for model in django admin panel
I want to add custom table to my model. I explored this question and found out that I should change change_list_results.html like this: {% load render_table from django_tables2 %} {% render_table table %} But I got bare table without sidebhars and so on. What did I do wrong? -
With Django Websockets, how can I subscribe the current user to a new group from views.py
In Django, I have models.py with Collection and Members as a relationship to them: # models.py class Collection(models.Model): name = models.CharField(max_length=100, null=False, blank=False) class Member(models.Model): account = models.ForeignKey(User, related_name="account_set", on_delete=models.CASCADE) collection = models.ForeignKey(Collection, related_name='members', on_delete=models.CASCADE) And I have a websocket for notifying members whenever we have changes in a collection that the user is member of. For that, I have MainConsumer, shown below. # consumers.py class MainConsumer(WebsocketConsumer): def connect(self): user_id = self.scope['user_id'] collection_ids = Member.objects.filter(account_id=user_id).values_list("collection_id", flat=True) for collection_id in collection_ids: async_to_sync(self.channel_layer.group_add)(f'collection_ws_{collection_id}' , self.channel_name) self.accept() Works like a charm. I can comunicate perfectly. Question is the following: If I create a new collection, I need somehow to tell my MainConsumer that the requested user should now receive notifications from this new collection as well. # views.py class CollectionCreate(generics.CreateAPIView): permission_classes = [IsAuthenticated, ] def create(self, request, *args, **kwargs): collection = Collection.objects.create(name=request.data['name']) # Create a member as admin member = Member.objects.create( collection=collection, account=request.user, ) ** -- Here I want to 'subscribe' the current user to this new collection as well, but I cant figure out how... -- ** return JsonResponse({"payload": CollectionSerializer(collection, many=False).data }, status=200) Worth mentioning that I could "reload" my websocket in the frontend and it works, but it seems a bit …