Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django csv import automatically
i'm Marcello from italy, i'm new in python and django. I ask a question to get info for my project in django. I've created a project that have two tables, my problem is that how get data automatically from csv, i will create an ftp server that stored csv.txt and update the tables (for example every day). Now i update with Django import / export manually. I would like that django read csv files and update db then delete. Thank you very much for all your support!!! my models.py: from django.db import models from django.urls import reverse class AnagraficaCliente(models.Model): codice_cliente = models.CharField(max_length=20, primary_key=True, null=False, unique=True) ragione_sociale = models.CharField(max_length=40) ragione_sociale_dest = models.CharField(max_length=40) nome = models.CharField(max_length=20, blank=True) cognome = models.CharField(max_length=20, blank=True) ragione_sociale = models.CharField(max_length=20) indirizzo = models.TextField(blank=True) cap = models.CharField(max_length=5, blank=True) piva = models.CharField(max_length=11, blank=True) vatnumber = models.CharField(max_length=13, blank=True) ragione_sociale_dest = models.CharField(max_length=40) indirizzo_dest = models.TextField(null=True) def __str__(self): #return self.ragione_sociale + " " + self.codice_cliente return self.ragione_sociale_dest + " " + self.indirizzo_dest class Meta: verbose_name = "AnagraficaCliente" verbose_name_plural = "AnagraficaClienti" class Tracking(models.Model): track = models.CharField(max_length=10, null=False, unique=True, primary_key=True) passaggio1 = models.CharField(max_length=50, blank=True) passaggio2 = models.CharField(max_length=50, blank=True) passaggio3 = models.CharField(max_length=50, blank=True) passaggio4 = models.CharField(max_length=50, blank=True) passaggio5 = models.CharField(max_length=50, blank=True) consegna = ( ('C', 'Consegnato'), … -
Regroup in django returning only one grouper - not iterating on regrouped list
I have a simple ListView of a Model with a DateTimeField, the Model is ordered by this field. In the template, I have the following code: {% regroup teamsession_list by tdate|date:"W" as weekly_list %} {% for training_week in weekly_list %} <div class="container"> {{training_week}}</div>{% endfor %} I wrote this to test the returned result. I have four weeks of data, but only one grouper returned in the template like so GroupedResult(grouper='48', list=[<TeamSession: xesr: performed on 2018-11-27 00:00:00+00:00>, <TeamSession: test4: performed on 2018-11-26 00:00:00+00:00>, <TeamSession: test5: performed on 2018-11-26 00:00:00+00:00>, <TeamSession: test: performed on 2018-11-26 00:00:00+00:00>]) Anyone with an idea why the other four week is not in the result? The view looks like this: class TeamWeeklyView(ListView): model=models.TeamSession template_name = 'teams/weekly.html' I know there is a weekly archive view, but its not suitable for my purposes. -
How to decode URL with Persian slug in Django 2.0?
I have an archive view that using Persian slug like: چینیها-خورشید-مصنوعی-هم-ساختند with this url pattern: urlpatterns = [ ... path('archive/<str:slug>/', views.ArchiveDetailView.as_view(), ... ] models.py: class Archive(models.Model): ... slug = models.SlugField(_('Slug'), max_length=128, unique=True, allow_unicode=True) ... views.py: class ArchiveDetailView(DetailView): model = Archive def get_object(self, queryset=None): slug = self.kwargs.get(self.slug_url_kwarg) return get_object_or_404(self.model, slug=slug) This work fine in local with Django built-in webserver. But when I deploy site on my host (cPanel) return 404 error (only for Persian slug). How can I fix it? -
Django radio form showing ['on'] for the POST values
When I working with Django forms, I need to get the selected radio button id on submit. But when I log the value of post data I came to see that request.POST selected radio as 'sample': ['on']. template/detail.html <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <input type="radio" name="sample" id="r1"> <label for="r1">Radio 1</label> <input type="radio" name="sample" id="r2"> <label for="r2">Radio 2</label> <br> <input type="submit" value="Vote"> </form> views.py print (request.POST) print result <QueryDict: {'csrfmiddlewaretoken': ['exomyfdxW1uPeZtZA46SgWG9UVxX8iY6SGypagSDmkYdeFcifCOXRiXQv2TIgp2A'], 'sample': ['on']}> Why is that coming like that is there any problem in my code. -
DRF - Authentication credentials were not provided
I am testing django rest framework using python requests module but its says an error. I am just beginner rest-api developer. DRF setting main.py import datetime REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ) } JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler', 'JWT_ALLOW_REFRESH': False, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', # Authorization: JWT <token> 'JWT_AUTH_COOKIE': None, } and my testing code is import os import json import requests AUTH_ENDPOINT = 'http://127.0.0.1:8000/api/auth/jwt/' ENDPOINT = 'http://127.0.0.1:8000/api/status/' image_path = os.path.join(os.getcwd(), 'drf.png') headers = { "Content-Type": "application/json" } data = { "username": 'jaki', "password": 'SADHIN101119' } r = requests.post(AUTH_ENDPOINT, data=json.dumps(data), headers=headers) token = r.json()['token'] headers = { "Content-Type": "application/json", "Authorization": "JWT" + token } post_data = json.dumps({"content": "some random content"}) posted_response = requests.post(ENDPOINT, data=post_data, headers=headers) print(posted_response.text) Error showing {"detail":"Authentication credentials were not provided."} How can i solve the problem. Thanks. -
ValueError - Python Django
I went through forums and did some changes in my codes but the problem is still there. I did migrate and makemigrations, and even deleted migrate and recreate it again. I also added default=0 to the models.py code: age = models.PositiveIntegerField(default=0) I'll appreciate you if you help me on this issue. These are some lines of codes, let me know if you need any other information. This is the error: ValueError at /basic_app/create/ invalid literal for int() with base 10: 'create' Request Method: GET Request URL: http://127.0.0.1:8000/basic_app/create/ Django Version: 2.1.2 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'create' Exception Location: C:\ProgramData\Miniconda3\envs\myDjanEnv\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 965 Python Executable: C:\ProgramData\Miniconda3\envs\myDjanEnv\python.exe Python Version: 3.7.0 Python Path: ['C:\\Users\\Administrator\\Desktop\\django_lecture\\djan_advance\\advcbv', 'C:\\ProgramData\\Miniconda3\\envs\\myDjanEnv\\python37.zip', 'C:\\ProgramData\\Miniconda3\\envs\\myDjanEnv\\DLLs', 'C:\\ProgramData\\Miniconda3\\envs\\myDjanEnv\\lib', 'C:\\ProgramData\\Miniconda3\\envs\\myDjanEnv', 'C:\\ProgramData\\Miniconda3\\envs\\myDjanEnv\\lib\\site-packages'] This is __init__.py file, line 960-965: def get_prep_value(self, value): from django.db.models.expressions import OuterRef value = super().get_prep_value(value) if value is None or isinstance(value, OuterRef): return value return int(value) The models.py file: from django.db import models # Create your models here. class School(models.Model): name = models.CharField(max_length=128) principal = models.CharField(max_length=128) location = models.CharField(max_length=128) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=128) age = models.PositiveIntegerField() school = models.ForeignKey(School,related_name='students',on_delete=models.PROTECT) def __str__(self): return self.name urls.py file in basic_app folder: from django.conf.urls … -
List Django database table names from external script
I am trying to access sqlite3 database that I have in my Django project from within external script that is not part of the project. However, the following will return an empty list: con = sqlite3.connect('database.db') cursor = con.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") print(cursor.fetchall()) Even though I have already saved some models to the database. To check the table names, I use the following in Django shell: >>> tables = connection.introspection.table_names() >>> seen_models = connection.introspection.installed_models(tables) >>> seen_models {<class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.sessions.models.Session'>, <class 'django.contrib.contenttypes.models.ContentType'>, <class 'explorer_api.models.Athlete'>, <class 'django.contrib.admin.models.LogEntry'>, <class 'django.contrib.auth.models.Group'>, <class 'explorer_api.models.Activity'>, <class 'django.contrib.auth.models.User'>} >>> tables ['auth_group', 'auth_group_permissions', 'auth_permission', 'auth_user', 'auth_user_groups', 'auth_user_user_permissions', 'django_admin_log', 'django_content_type', 'django_migrations', 'django_session', 'explorer_api_activity', 'explorer_api_athlete'] I have specified the table names explicitly in model's Meta, so I guess the table names are appname_modelname (explorer_api_activity and explorer_api_athlete). But why the empty list? -
Passing default paramter value to view method in django is not working
I am very new to Django. I am trying to use an URL with optional parameter, If I pass an URL including the optional Parameter, everything works as expected, but when I try to use an URL without the optional parameter I am getting a 404 page not found error. My urls.py file content from coffeehouse.stores import views as stores_views urlpatterns = [ url(r'^store/(?P<store_id>\d+)/',stores_views.details) ] stores/views.py file content def details(request, store_id='1'): store_info={ 'store_id':store_id } return render(request, 'stores/details.html',store_info) I am unable to figure out why the default parameter is not considered. I am using Django 1.11, I am not sure if there is anything related to the version of Django. -
Django test send post request to next url
I am writing a test case where after login user redirects to the form which is being called by middleware and shown to user. So now user has to submit the form after which on submitting user redirects to normal page. middleware.py def process_view(self, request, view_func, *view_args, **view_kwargs): if condition: ... ... return redirect('%s?next=%s' % (reverse('form'), request.path)) else: return None form.html <form action="{% url 'form'%}" method="post"> <div> <input type="radio" id="yes" name="is_accepted" value="yes" onchange="activateButton(e)" checked> <label for="input1" >Yes</label> <br> <input type="radio" id="no" name="is_accepted" value="no" onchange="activateButton(e)"> <label for="input2">No</label> <input type="hidden" id="next" name="next" value="{{ next }}"> <button type="submit" name="submit" id="submit">Submit</button> </div> </form> As soon as form data is submitted the middleware should exit and return to normal or next page. Its working normal in browser but while test the form is shown but data is not been save on post request. response = client.post(form_url, {'is_accepted': 'yes'}, follow=True) After sending the post request still the response content is the form content. -
Is virtual environment in Django different in different Operating Systems?
I'm a beginner in web programming. I've been working on a Django project along with my teammates. I'm using Mac and he's using Ubuntu. I want to know if the virtual environment created in my system will work on his machine if I sent him mine. Is it differently built on different Operating systems? -
How to write queryset across 3 tables in Django?
I want to write queryset across 3 tables. (models are shown as below) As outcome, I want to get below information. {"naming1":"lpd1","naming2":"lpd2",...} Can anyone tell me how to write this query? models.py class zone(models.Model): zone=models.CharField(max_length=20) def __str__(self): return self.zone class light(models.Model): zone=models.OneToOneField(zone, primary_key=True, on_delete=models.CASCADE) lpd=models.IntegerField() <=extract class naming(models.Model): zone=models.ForeignKey(zone) naming=models.CharField(max_length=20) <=extract -
crispy form - Django SelectDateWidget
Am using crispy forms and SelectDateWidget in django. This is my sample form class SignupForm(ModelForm): class Meta: model=NGO fields=['Organization_Name','Contact_Person','Email_id','Mobile_no','Address','City','Pincode','Website','Established_on'] widgets = { 'Address': forms.Textarea, 'Email_id':forms.EmailInput,'Established_on':forms.SelectDateWidget(years=range(1900,datetime.today().year+1)) } In my html am accessing the Established_on field as {{ form.Established_on | as_crispy_field }} But it displays in vertical View. I tried with {{ form.Established_on_day | as_crispy_field }} But it gives error "as_crispy_field got passed an invalid or inexistent". I want to display Month,Day and Year in a Single Row. -
Creating A Timer For an Academic Quiz
I am creating a web app that's supposed to ask 90 questions in 180 mins. The backend uses Django, while the frontend uses the trio of HTML, CSS and Jquery, Javascript. I've managed to implement the display and entering the questions part. However I'm having issues implenting the timer part. Specifically, I've no idea what should I use to create the timer, the backend or the frontend. Also how to implement it? Thanks! -
Django 2.1 passing a variable to template,
Have a question here about passing a variable into a Django template. The goal is to filter a set of photos based off the type of photography. I initially wanted to do it from S3 and the folder that it was in, but that's a little beyond my skill at the moment. I went with just creating different url's that account for that. The issue I'm having is that I'd like to pass the variable into the template that extends the base_layout.html, but it won't render anything for that variable. Am I just miss-understanding how to do it? Model.py from django.db import models # Create your models here. class Gallery(models.Model): title = models.CharField(max_length = 50) body = models.TextField(max_length = 500) created = models.DateTimeField(auto_now_add = True) thumb = models.ImageField(default = 'default.jpg', blank = True) slug = models.SlugField(blank = True) order = models.CharField(max_length = 2, blank = True) def __str__(self): return self.title def body_preview(self): return self.body[:50] class photoUrl(models.Model): url = models.CharField(max_length = 128) uploaded_on = models.DateTimeField(auto_now_add = True) class Photos(models.Model): title = models.CharField(max_length = 50) picture = models.ImageField(blank = True) created = models.DateTimeField(auto_now_add = True) catagory = models.CharField(max_length=256, choices=[('wedding', 'wedding'), ('portrait', 'portrait'), ('landscape', 'landscape'), ('boudoir', 'boudoir'),], blank = True) def __str__(self): return … -
Saving an unknown object type into database in Django
I have the following model: class Parameter(models.Model): par_type = = models.CharField(max_length=30) value = models.TextField() Majority of the time the value field will store a number (value=3.2118). But sometimes I want to assign a list of other object IDs (like value="[32, 22, 45]") or a string object (like value="pass"), etc. I will use value field in functions like the ones below based on the value of par_type: def foo(par): # par is a Parameter object. return float(par.value) / 2 def bar(par): # Some code to convert a par to a list of objects object_list = get_objects(par) # Return a random object from list return random.choice(object_list) I don't want to write a piece of code for every possible object type. Ideally there is one decompose() function to use everywhere. I thought of saving object as pickle or JSON type (saw it from here). But I couldn't figured out how to do it. I'm using MySQL db. -
Replacing long polling with message broker for a django app
I have django rest api which among other things have messaging functionalities. Currently the get messages for an user and get all rooms for an user are being done by long polling every 10 seconds. I want to change this to a message broker architecture. Can someone conceptually help me understand how does a message broker work and who calls the get endpoints based on what? -
Django Admin Extra Fields In get_queryset
I have Django 1.11 app that tracks Phones, Sim Cards, Data Usage of Sim Cards and the association of a Sim Card to a Phone like the following: #model to display information for all Phones class Phone(models.Model): serialnumber = models.CharField(max_length=255) brand = models.CharField(max_length=255) #model to display information for all sim cards class Sim(models.Model) iccid = models.CharField(max_length=255) msisdn = models.CharField(max_length=255) #model to display daily data usage for all sim cards class DataUsage(models.Model) date = models.DateTimeField() sim = models.ForeignKey(Sim) data_usage_can = models.FloatField() data_usage_us = models.FloatField() data_usage_other = models.FloatField() #model to make an association from a phone to a sim. This will include sims with no phones and phones with no sims as well #all sims and phones are unique class Association(models.Model): phone = models.ForeignKey(Phone) sim = models.ForeignKey(Sim) transaction_date = models.DateTimeField() My goal is, in the Django Admin page of the Association model, to display two additional fields that are not in model itself, namely "Cycle to Date Usage" (ctd_usage) and "Transaction to Date Usage" (t_usage). ctd_usage should get all data usage for a sim from the 1st of the current month, up to the current date, and t_usage should get all data usage for a sim from the 1st of the month … -
Django: Displaying appointment linked to a particular user on their profile only
I have a model in Django called 'Booking' to book appointments, where there are two user fields: an expert, and a user which both have ForeignKey relationships. I also have a CustomUser model and each user has a profile page. How can I specify that I want to view only the appointments linked to that particular user (or expert) on their profile page? models.py: class Booking(models.Model): user = models.ForeignKey(CustomUser, null=True, default='', on_delete=models.CASCADE) expert = models.ForeignKey(CustomUser, null=True, default='',on_delete=models.CASCADE, related_name='bookings') title = models.CharField(max_length=200, default='Video call with ..', null=True) start_time = models.DateTimeField('Start time') end_time = models.DateTimeField('End time') notes = models.TextField('Notes', help_text='Please provide some detail on what you would like to learn or discuss', blank=True, null=True) views.py: class BookingView(CreateView): model = Booking form_class = BookingForm def view_profile(request, pk=None): if pk: user = CustomUser.objects.get(pk=pk) else: user = request.user args = {'user': user} return render(request, 'profile.html', args) The profile displays all of the user objects fine, but I'm not sure how to call the user-linked booking objects only on the profile page. Any help would be appreciated!! -
Django Database Settings Reading From Base File
I have my Django application configured to use sqlite in the base settings file and I overwrite the setting in the production and development settings files. I set DJANGO_SETTINGS_MODULE to the correct value in my Dockerfile. However, when I run it, it uses sqlite as defined in the base settings file. If I comment it out I it complains about database.ENGINE not being set. Why is it reading the database configuration from the base.py settings file rather than the other? I specify the other in the environment variable and it's reading other settings from there but for the database it reads it from the base file. I'm somewhat confused by this behavior, if anyone could give me some direction towards solving this issue it would be appreciated. If you need any more information let me know. -
A custom argument in graphene-django
How do I create a custom argument in GraphQL with graphene-django? I currently have this configuration in my schema.py: class Post(DjangoObjectType): class Meta: model = FeedPost interfaces = (graphene.relay.Node,) filter_fields = ['id'] class Query(graphene.ObjectType): post = graphene.Node.Field(Post) def resolve_post(self, info, **kwargs): username = kwargs.get('username') u = User.objects.get(username=username) users_sources = FeedSource.objects.filter(user=u) return FeedPost.objects.filter(feed__feedsource__in=users_sources).annotate( source_title=F('feed__feedsource__title') ) schema = graphene.Schema(query=Query) But I have not been able to figure out how to make "username" a required argument in the actual GraphQL query on "post". -
How to restart heroku app without killing unfinished celery tasks
I have a django web application on heroku in which several celery tasks may be running in the background. Redis is used as a broker. The problem is, that when I restart the heroku application either with heroku restart or by deploying with heroku container:release while some tasks are being executed, they are killed with SIGTERM which means the tasks are never finished. 2018-11-23T19:35:24.506833+00:00 heroku[beat.1]: Restarting 2018-11-23T19:35:24.507645+00:00 heroku[beat.1]: State changed from up to starting 2018-11-23T19:35:24.517551+00:00 heroku[web.1]: Restarting 2018-11-23T19:35:24.518013+00:00 heroku[web.1]: State changed from up to starting 2018-11-23T19:35:24.528684+00:00 heroku[worker.1]: Restarting 2018-11-23T19:35:24.529175+00:00 heroku[worker.1]: State changed from up to starting 2018-11-23T19:35:24.952139+00:00 app[worker.1]: 2018-11-23T19:35:24.952156+00:00 app[worker.1]: worker: Warm shutdown (MainProcess) 2018-11-23T19:35:24.949622+00:00 heroku[worker.1]: Stopping all processes with SIGTERM 2018-11-23T19:35:24.996307+00:00 heroku[worker.1]: Process exited with status 143 2018-11-23T19:35:25.456920+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2018-11-23T19:35:25.480748+00:00 app[web.1]: [2018-11-23 19:35:25 +0000] [16] [INFO] Handling signal: term 2018-11-23T19:35:25.481026+00:00 app[web.1]: [2018-11-23 19:35:25 +0000] [19] [INFO] Worker exiting (pid: 19) 2018-11-23T19:35:25.481491+00:00 app[web.1]: [2018-11-23 19:35:25 +0000] [20] [INFO] Worker exiting (pid: 20) 2018-11-23T19:35:25.481519+00:00 app[web.1]: [2018-11-23 19:35:25 +0000] [21] [INFO] Worker exiting (pid: 21) 2018-11-23T19:35:25.623274+00:00 heroku[web.1]: Process exited with status 143 2018-11-23T19:35:25.816061+00:00 heroku[beat.1]: Stopping all processes with SIGTERM 2018-11-23T19:35:25.928498+00:00 heroku[beat.1]: Process exited with status 143 From what I found on the internet, the warm shutdown caused … -
Why am I getting an error pushing django code to heroku?
When I try to push my code for a Django site to Heroku, I am getting the following error: remote: /usr/bin/ld: /app/.heroku/python/lib/libpython3.6m.a(ceval.o): relocation R_X86_64_PC32 against symbol `_Py_NoneStruct' can not be used when making a shared object; recompile with -fPIC remote: /usr/bin/ld: final link failed: Bad value remote: collect2: error: ld returned 1 exit status remote: error: command 'gcc' failed with exit status 1 remote: remote: ---------------------------------------- remote: Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-hq2rsseo/mod- wsgi/setup.py';f=getattr(tokenize, 'open', open) (__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-4wci3c07-record/install-record.txt --single-version- externally-managed --compile" failed with error code 1 in /tmp/pip- build-hq2rsseo/mod-wsgi/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to stormy-stream-43261. remote: To https://git.heroku.com/stormy-stream-43261.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/stormy- stream-43261.git' I think it has something to do with Heroku not supporting some dependency, but regardless, I can't figure out what to do to resolve this issue. Any ideas? -
python-crontab ask for privileged user in django request
I'm trying to automate crontab to receive a request and create a job from django and I'm get the following error: Traceback: File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/var/www/myweb/apps/general/views.py" in create_cronjob_json 779. return create_cronjob(request) File "/var/www/myweb/apps/utilities/daemons_planner.py" in create_cronjob 12. cron = CronTab(user="pedro") File "/var/www/venv/lib/python3.6/site-packages/crontab.py" in __init__ 227. self.read(tabfile) File "/var/www/venv/lib/python3.6/site-packages/crontab.py" in read 288. raise IOError("Read crontab %s: %s" % (self.user, err)) Exception Type: OSError at /create-cronjob-json/ Exception Value: Read crontab pedro: b'must be privileged to use -u\n' I am using python-crontab This is my code: def create_cronjob(request): received_json_data = json.loads(request.body) cron = CronTab(user="pedro") comment = received_json_data['name'] command = received_json_data['command'] band = True for job in cron: if job.comment == comment: band = False if band: job = cron.new(command=command, comment=comment) job.setall(received_json_data['cron']) cron.write() response_data = {} response_data["success"] = True return JsonResponse(response_data) What might be the problem? How could I tackle the issue? -
Django - Admin - Dependent fields
in my django-admin detail i have two select fields (foreign keys): Via the first one i can select a Customer (object) Via the second one i can select a CustomerAddress (object) When i select the Customer A, i only want to present customer addresses which belong to this specific Customer A. When i select the Customer B, i only want to present customer addresses which belong to this specific Customer B. But django-admin loads all customer_addresses into the second select field. How can i make these two fields dependent on each other? thanks and greetings! -
Djano - right way to join not-django tables
I have old cms database, structure isn't perfect and it can't be modified but i need to query using django TABLE posts (post_id) TABLE posts_text (post_id, post_text) TABLE episode (id, season_id, episode_name) TABLE episode_post_relationship (id, season_id, episode_id, post_id) Please help me to create django models with right fields reference. Should i use OneToOneField, ForeignKey, ManyToManyField and etc or pure join? I'm trying to get Episodes from episode_post_relationship table with posts_text.posts_text and posts.some_other_col but can't specify that episode_post_relationship table should join posts_text on post_id and the same for posts table.