Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR (EXTERNAL IP): Invalid HTTP_HOST header 'check.proxyradar.com'
Everything worked very very well untill I got this error message: Invalid HTTP_HOST header: 'check.proxyradar.com'. You may need to add 'check.proxyradar.com' to ALLOWED_HOSTS. Report at /azenv.php Invalid HTTP_HOST header: 'check.proxyradar.com'. You may need to add 'check.proxyradar.com' to ALLOWED_HOSTS. And because of this error I get Server Error (500). Please, help me, people, how can I fix this error, this vulnerable server proxyradar ? Here is my nginx configuration: server { listen 80; server_name .forexample.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/me/project; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
How to setup confirmation alert box inside django view?
Above picture is an example of what i am looking for . I need to perform confirmation from user , using alert box from view . Requirements : Inside the view , i need to perform a confirmation and based on the confirmation ,i want to check two conditions -
How to upload a Excel sheet in Angular and receive it in Django
I'm new to Angular and Django. My requirement is to build a webpage, from which user can upload a excel sheet. I need to receive this excel sheet in back-end (Django) and perform operations on that file. I checked various examples but somehow I couldn't do it. html.ts .. </form> <input type="file" (change)="selectExcel($event)"> <button type="button" (click)="uploadExcel()">Upload Excel</button> </form> Component.ts selectExcel(event){ this.selFile=event.target.files[0] } uploadExcel(){ console.log(this.selFile) const fd = new FormData(); fd.append('file', this.selFile,this.selFile.name); console.log(fd) this.service.fileUpload(fd) .subscribe(res=>{ console.log(res) }) } service.ts fileUpload(f){ return this.http.post(this.API+'fileupload/',JSON.stringify(f)) } } I'm really not sure how to receive the file in Django.. I tried the below def post(self, request): file = json.loads(request.body) print(file) -
Django regex works only if the caret is typed into the address abr
I'll preface this by saying that I'm a designer trying to learn to code. Now that that's out of the way… My urls.py looks like this: urlpatterns = [ path(r'^admin/', admin.site.urls), ] but I get a 404 that says: Django tried these URL patterns, in this order: ^admin The current path, admin/, didn't match any of these. However, if I type the URL as http://127.0.0.1:8000/^admin/, which sanitizes to http://127.0.0.1:8000/%5Eadmin/, I can see the admin dashboard. Why is the regular expression not working here? Does something need to be imported? -
How to aggregate model property?
version Django == 1.11. I have a Model that save code and need to get shortest code without comment. class Model(models.Model): code = models.TextField() @property def uncomment_code(self): uncommment_code = re.sub(re.compile(r"#.*[\n\\Z]"),"", code) return uncomment_code I want to find shortest code without comment. For example #include<stdio.h> int main(){ int a, b; scanf("%d %d", &a, &b); printf("%d", a-b); return 0; } ------ >>>>> this code will be change below one int main(){ int a, b; scanf("%d %d", &a, &b); printf("%d", a-b); return 0; } then aggregate Model.objects.all().annotate(code_len=Length('uncomment_code')).aggregate(shortest_code_len=Min('code_len'))['shortest_code_len'] this is not work, i know property can not use in queryset. do you have any other idea? i can't add model field for uncomment_code. -
How can send mail to user so user can get confirmation (his account is created) in Django admin
Code: def email_new_user(sender, **kwargs): if kwargs["created"]: # only for new users send_mail('New notification','Your accont is created.','abcd@gmail.com',[user_email], fail_silently=False,) post_save.connect(email_new_user, sender=User) -
how to load .sql file into django model?
Loaded data into database using the below command but still cant see the data in Django admin models psql postgres -U admin {db_name} < {dump.sql} -
Django FORCE_SCRIPT_NAME in settings
i am struggling to find information what the below code does: if set_prefix: set_script_prefix( '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME ) What are thread local-url resolvers scripts? Is it setting the prefix of those scripts? What significance does it have, does it have something to do with configuration of webservers and environmental variables? from django.utils.version import get_version VERSION = (3, 0, 1, 'alpha', 1) __version__ = get_version(VERSION) [docs]def setup(set_prefix=True): """ Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True. """ from django.apps import apps from django.conf import settings from django.urls import set_script_prefix from django.utils.log import configure_logging configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) if set_prefix: set_script_prefix( '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME ) apps.populate(settings.INSTALLED_APPS) -
Django - multiple models(table) in one view
I want to show this models. like thisenter image description here but i don't know. How can i do that. I tried to solve this problem for 3months :( already I have MySQL Database. So, I have to stay these Data Structure(Models) Admin Inheritance? Override Queryset in Django Admin? I don't know how to do that. I didn't under stand Queryset,str,ORM... Because I just have started Django for 3months. I have to fix this problem. Multiple models(table==class) in one view(templates) But I can't.. Please Tell me the hint, Solution, anything from django.conf import settings from django.db import models from django.utils import timezone class Exam(models.Model): idexam = models.IntegerField(primary_key=True) trueanswernum = models.IntegerField(db_column='trueAnswerNum', blank=True, null=True) # Field name made lowercase. falseanswernum = models.IntegerField(db_column='falseAnswerNum', blank=True, null=True) # Field name made lowercase. exammain = models.TextField(db_column='examMain', blank=True, null=True) # Field name made lowercase. questionsubmain = models.TextField(db_column='questionSubMain', blank=True, null=True) # Field name made lowercase. answerno1 = models.TextField(db_column='answerNo1', blank=True, null=True) # Field name made lowercase. answerno2 = models.TextField(db_column='answerNo2', blank=True, null=True) # Field name made lowercase. answerno3 = models.TextField(db_column='answerNo3', blank=True, null=True) # Field name made lowercase. answerno4 = models.TextField(db_column='answerNo4', blank=True, null=True) # Field name made lowercase. rightanswer = models.IntegerField(db_column='rightAnswer', blank=True, null=True) # Field name made lowercase. originalremark = models.TextField(db_column='originalRemark', … -
serving static angularjs application files from django
I have written the backend using django and i am trying to server the angularjs application from my django application. I have copied the the static build of front end angularjs to the static folder, and that has following file structure: static UI assets img scripts styles json-data 3rdpartylicenses.txt icon.b60bba990bea07f9376c.eot , devManifest.yml favicon.ico, fontawesome-webfont.674f50d287a8c48dc19b.eot, main.e7b9143f2f482d6d3cc7.js fontawesome-webfont.912ec66d7572ff821749.svg polyfills.f3fc5ca24d1323624670.js runtime.a66f828dca56eeb90e02.js scripts.5bde77e84291ce59c080.js Staticfile styles.38614f36c93ac671679e.css styles0.38614f36c93ac671679e.css and in template folder : my index.html goes like this: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>DCMS(Data Center Management System)</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="{% static 'favicon.ico' %}"> <link rel="stylesheet" href="{% static 'styles.38614f36c93ac671679e.css' %}"></head> <body> <app-root></app-root> <script type="text/javascript" src="{% static 'runtime.a66f828dca56eeb90e02.js' %}"></script> <script type="text/javascript" src="{% static 'polyfills.f3fc5ca24d1323624670.js' %}"></script> <script type="text/javascript" src="{% static 'scripts.5bde77e84291ce59c080.js' %}"> </script><script type="text/javascript" src="{% static 'main.e7b9143f2f482d6d3cc7.js' %}"></script> </body> </html> i have made the required changes for static files in django settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/UI'), 'static/assets', ] I am able to serve the application and see index.html, but the problem is there are some scripts and images inside assets folder which are not getting displayed. What am i missing? -
TypeError in Django models, It seems like there's some problem in fields but dont know what
I'm facing this issue. It seems like there's some problem in the fields. but I don't know which field. I've checked all the fields one by one, but everything is working. but when I'm opening contact, which is a wrapper around other fields, it's throwing me this error. Environment: Request Method: GET Request URL: http://localhost:8000/admin/contact_management/contact/11/change/ Django Version: 2.2.2 Python Version: 3.7.5 Installed Applications: ['django.contrib.admin', 'accounts', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework_filters', 'AreaManagement', 'contact_management', 'telecaller', 'django_extensions', 'django_better_admin_arrayfield.apps.DjangoBetterAdminArrayfieldConfig', 'admin_reorder', 'rest_framework', 'rest_framework.authtoken', 'djoser', 'corsheaders', 'django_filters', 'phonenumber_field', 'utils', 'control_panel', 'background_task', 'crm', 'website', 'rest_framework_swagger'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'admin_reorder.middleware.ModelAdminReorder', 'corsheaders.middleware.CorsPostCsrfMiddleware'] Template error: In template /media/charanjit/WorkStation/BNHABITAT_ENV/lib/python3.7/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 15 __str__ returned non-string (type __proxy__) 5 : {% endif %} 6 : {% for line in fieldset %} 7 : <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> 8 : {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and … -
what is the error in this django database?
raise ValueError('The database backend does not accept 0 as a ' ValueError: The database backend does not accept 0 as a value for AutoField. This is the error that has occured while making migrations. from django.db import models # from modules.volunteer.volunteer_models.models import volunteerRegistration the below code is model.py .i would prefer some help guys. class cause(models.Model): class Meta: db_table = 'tbl_cause' verbose_name_plural = 'causes' name = models.CharField(max_length=50) description = models.TextField() date = models.DateField(auto_now=False) volunteer_no = models.IntegerField() status = models.CharField(max_length=50) applied_date=models.DateField(auto_now=True) def __str__(self): return ('%s' % (self.name)) -
A single url for many urls with common ending
I want to submit a form from any page. For that I have kept the form in base.html. But when a user submits the form, it redirects to a page with different url from different page. For an example, when user is on localhost:8000/example1/page1/ and click submit button it takes to the url localhost:8000/example1/page1/submit.. when user is on localhost:8000/example2/page2/something/else/ and click submit button it takes to the localhost:8000/example2/page2/something/else/submit.. One solution that I can think of is to have all these urls in my urls.py file to ensure smooth routing. But I feel that's not the right way to do. Second solution I think of is to put a button to redirect to the form on the base html so that it appears on all page and when a user has to fill the form he can click it and go. But I want the form to appear on every page on the sidebar. Any suggestion would be highly helpful. Thanks. -
Divio App trouble to create project directory and clone repository
Please help I have trouble with Divio App trying to making it work. When I press "set up project" it gives me this * Creating workspace cloning project repository Cloning into '/c/Users/Ubisoft/Documents/iloveit'... Bad owner or permissions on /home/divio/.ssh/config fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. There was an error trying to run a command. This is most likely not an issue with divio-cli, but the called program itself. Try checking the output of the command above. The command was: git clone git@git.divio.com:iloveit.git /c/Users/Ubisoft/Documents/iloveit * and in windows power shell it gives me this Creating workspace cloning project repository Cloning into '/c/Users/Ubisoft/Documents/iloveit'... Bad owner or permissions on /home/divio/.ssh/config fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. ------------------------------------------------------------------------------------------------------------------------ There was an error trying to run a command. This is most likely not an issue with divio-cli, but the called program itself. Try checking the output of the command above. The command was: git clone git@git.divio.com:iloveit.git /c/Users/Ubisoft/Documents/iloveit divio@app-1.0.0 /c/Users/Ubisoft/Documents $ -
Dynamic Table row with select option
My html <select onchange="doTheInsert" id="items"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <table id="myTable"> <tr> <td class="tdnb" colspan="21"><input id="myInput" type="text" placeholder="Search Student" class="search"></td> </tr> <tr id="tr"> <td colspan="1" class="tdhead" >Student Name</td> <td class="tdcell2">Average</td> </tr> <tbody> {% for student in teacherStudents %} <tr> <td colspan="1" class="tdcell">{{ student.Students_Enrollment_Records }}</td> </tr> {% endfor %} <tr> <td class="tdbtn" colspan="21"><button type="button" class="save">&plus;&nbsp;Save</button> &nbsp;<button type="button" class="save">&check;&nbsp;Finalize</button></td> </tr> </tbody> </table> If the user selected the option number 1 and if the user selected the option number 3 this is my html script <script> function doTheInsert() { var e = document.getElementById("items"); var strUser = e.options[e.selectedIndex].text; alert(e) for (i = 0; i <= strUser-1; i++) { var newRow=document.getElementById('tr').insertRow(1); newRow.innerHTML = ""<th style='background-color: #ccc;color: #000000;text-align:center;font-size: 16.5px'> <input type='date' name=''style='border: none; font-size:12px; padding: 0; '></th>"; } } </script> -
'int' object has no attribute get Error when access multivalue django
I want to access multivalue that has in the same id / class in some elements i will give some code to make it clear html <div class="row mt"> <div class="col-lg-12"> <div class="form-panel"> <form class="form-horizontal style-form" action="#"> <div class="form-group"> <label class="control-label col-md-3">Database Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id = "tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> <!-- <li><a href="#"></a></li> --> {% for table in obj2 %} <option value = "{{table}}" >{{ table }}</option> {% endfor %} <!-- <li><a href="#">Dropdown link</a></li> --> </option> </select> </div> </div> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Table Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> </select> </div> </div> </div> </div> <div class="form-group"> <button class="btn btn-theme" onclick="return appendBox()">Add</button> <label class="control-label col-md-3">Column Name</label> <div class="col-md-4" id ="test"> <div class="btn-group"> <select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> </select> </div> </div> </div> <div class="form-group"> <button class="btn btn-theme" onclick=" return appendFilterBox()">Add</button> <label class="control-label col-md-3">Filter</label> <div class="col-md-4" id="filtbox"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select class="conditionselect" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;"> </select> <select id="operator" style="width:120px;background-color:white;height:30px;font-size:15px;text-align-last:center;"> <option> > </option> <option> < </option> <option> ≥ </option> <option> ≤ </option> <option> = </option> </select> <input id="parameter" type="text" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;"> </input> </div> </div> </div> </div> <div class="form-group"> <div class="col-md-4" id="showquery"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <button id="result" class="btn btn-theme" type="submit" style="height:30px;width:100px;" … -
Why is Django FieldFIle readline() returning the hex version of a text file?
Having an odd problem. I have a Django app that opens a file (represented as a Django FieldFile) and reads each row using readline() as below: with file.open(mode='r') as f: row = f.readline() # do something with row... The file is text, utf-8 encoded and lines are terminated with \r\n. The problem is each row is being read as the hex representation of the string, so instead of "Hello" I get "48656c6c6f". A few stranger things: It previously worked properly, but at some point an update has broken it (I've tried rolling back to previous commits and it is still wonky, so possibly a dependency has updated and not something from my requirements.txt). Missed it in my testing because it is in a very rarely used part of the app. If I read the same file using readlines() instead of readline() I see the correct string representation of the file wrapped in [b'...'] The file reads normally if I do it using straight Python open() and readline() from an interpreter Forcing text mode with mode='rt' doesn't change the behaviour, neither does mode='rb' The file is stored in a Minio bucket, so the defaut storage is storages.backends.s3boto3.S3Boto3Storage from django-storages and not … -
Django 2.2.4 -- 5 hours of reading/stack-overflowing and still cannot get ORM to work as expected
I have created a super simple example to show my issues. class TestModel(MyModel): # MyModel simply adds a UUID id and created_at/updated_at... shape = models.CharField(db_index=True, max_length=100, null=False) color = models.CharField(db_index=True, max_length=100, null=False) class Meta: db_table = 'test_model' I put in some content... select * from test_model; id | created_at | updated_at | shape | color --------------------------------------+----------------------------+------------+-----------+------- 92a04279-9dd5-40c8-a056-052456df4e56 | 2019-12-16 14:44:21.363-05 | | Circle | Red 3100ed61-056a-4da1-a537-df32496c658a | 2019-12-16 14:44:21.363-05 | | Square | Blue 61e2a86a-97ef-4530-a8bb-601411280ff9 | 2019-12-16 14:44:21.363-05 | | Heart | Blue 3fb19a51-9e10-4214-ad63-22422e2b77f6 | 2019-12-16 14:44:21.363-05 | | Hexagon | Red 945356ab-d375-4a3b-aafc-e20c5f79f6c3 | 2019-12-16 14:44:21.363-05 | | Rectangle | Blue 96dcfef1-7668-44da-97cc-a86e419d6936 | 2019-12-16 14:44:21.363-05 | | Trapeze | Red What I want is simple. I want to know how many shapes of each distinct colors there are. So in SQL I write... select color, count(shape) from test_model group by color; color | count -------+------- Red | 3 Blue | 3 Trying to do the same with Django/ORM/Annotate simply does not work, no matter what I try. My last attempt: colors = TestModel.objects.annotate(color_count=Count('color', distinct=True)) for item in colors.all(): print(item.color + " " + str(item.color_count)) But I get this... Blue 1 Red 1 Blue 1 Red 1 Blue 1 Red 1 … -
"(111: Connection refused) while connecting to upstream, client: " | Django, Gunicorn, Nginx - Server Error(500)
I have deployed my django app, but have a 500 error. When i type in the home url "mysite.com", it comes with the error and does not load, but when i type in "mysite.com/careers", or "mysite.com/sell", which happen to be fully static pages, it comes up beautifully. The home page, and other pages which have dynamic data do not serve. Afer reading some related questions, it seems to be a Gunicorn issue. What could be the issue here? Below is the error log from Nginx. Nginx Error log: 2019/12/16 17:30:15 [error] 20605#20605: *1370 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: xxx.xxx.xx.xx, server: xxx.xxx.xxx.xxx, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "mysite.com" nginx .conf file: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## client_max_body_size 0; proxy_max_temp_file_size 0; proxy_buffering off; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; ... } nginx sites available file: server { listen 80; server_name xxx.xxx.xxx.xxx mysite.com www.mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangoadmin/pyapps/MySite; } location /media/ { root /home/djangoadmin/pyapps/MySite; } location / { include … -
Call a script within a view PYTHON / DJANGO
I'm very new in Python and Django or the code in general I created a view that get value from an html template with javascript. With these values collected i want to run a script that consider these new values @csrf_exempt def register(request): type_list=request.POST.get('selected_type').split("&") #array collected from checkboxes from_date=request.POST.get('start_date').replace("&","") #date collected to_date=request.POST.get('end_date').replace("&","") #date collected import transaction.query #script I want to run profiling = transactionprofiling.objects.all() #database/model updated with the script tmpl = loader.get_template("transaction/index.html") cont = {'profiling': profiling} return HttpResponse(tmpl.render(cont)) #return the model in the template The definition doesn't work as it doesn't save the value "type_list" "from_date" "to_date" I made some research but nothing shows up thank you in advance for your help ! -
How to get a specific attribute from an object in the database in Python Django?
For an assignement I have to create a website where a user can add other users from the database as his friends. To accomplish that I'd like to create a dropdownlist where the user can select other users under their firstname + lastname. However, how do I create a list with all user's names in it ? How do I make the drop down list ? Here is my models.py class User(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=50) country = models.CharField(max_length=50) email = models.EmailField(max_length=50) phone = models.CharField(max_length=30) password = models.CharField(max_length=128) GENDER_CHOICES = ( ('M','Male'), ('F','Female'), ('X','X'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) Here is my register_view in views.py : def register_view(request): if 'email' in request.GET: newUser = User(firstname=request.GET['firstname'], lastname=request.GET['lastname'], country=request.GET['country'], email=request.GET['email'], phone=request.GET['phone'], password=request.GET['password'], gender=request.GET['gender']) newUser.save() return redirect('/login') else: return render(request, 'register.html') Please, help… I deeply apologize for my silly questions and my English since it is not my mother tongue. I however really need at least a breakthrough concerning this. Many thanks ! -
FileNotFoundError when users try to upload a photo
I receive FileNotFoundError error messages when users try to sign up to my website and upload a photo. The error messages are like: [Errno 2] No such file or directory: '/tmp/<file_name>.upload.jpg' Where <file_name> is a random file name. I received a few messages like this recently and these users were not able to upload a photo and complete the registration (a user must have a profile photo to become an active member on Speedy Match). Do you know what is the problem? I'm using Django 2.1.15 with Python 3.6.8. I checked now with Chrome and Firefox and I was able to sign up to my website and upload photos. Most of the users who signed up to the website uploaded a photo successfully. But it failed for some specific users recently. Here is some code: def clean_photo(self): photo = self.files.get('photo') if (photo): speedy_match_accounts_validators.validate_photo_for_user(user=self.instance.user, photo=photo) else: photo = self.instance.user.photo speedy_match_accounts_validators.validate_photo_for_user(user=self.instance.user, photo=photo, test_new_photo=False) return self.cleaned_data def save(self, commit=True): if (commit): if ('photo' in self.fields): if (self.files): user_image = Image(owner=self.instance.user, file=self.files['photo']) user_image.save() self.instance.user.photo = user_image for field_name in self.user_fields: if (field_name in self.fields): setattr(self.instance.user, field_name, self.cleaned_data[field_name]) self.instance.user.save() super().save(commit=commit) def validate_photo_for_user(user, photo, test_new_photo=True): validate_photo(photo=photo) if (test_new_photo): user._photo = user.photo photo_is_valid = False try: if … -
Two slugs in url
I want to have a url pattern that takes 2 slugs. I'm trying to make it look like http://127.0.0.1:8000/category/model but I'm having difficulties understanding how to do this. Below is what I have so far: models.py def model_detail_view(request, category_slug, model_slug): model = Model.objects.get( category__slug=category_slug, model_slug=model_slug) context = { "model": model, } return render(request=request, template_name='main/model_detail.html', context=context) urls.py path("<str:category_slug>/<str:model_slug>/", views.model_detail_view, name="model_detail_view"), models.py class Category(models.Model): title = models.CharField(max_length=50) featured_image = models.ImageField(upload_to="categories") category_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Categories" def __str__(self): return self.title class Model(models.Model): title = models.CharField(max_length=80) category = models.ManyToManyField(Category) featured_image = models.ImageField(upload_to=image_dir) model_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Models" def __str__(self): return self.title -
How to implement comments in Django attached to a user
I am attempting to add comments to posts (in this site posts are called beets) and would like each comment to be from a user and attached to that user. A user should have a list of comments they have made. The post the comment is on should show the comments as well. I have gotten as far as I can add comments through the admin page, but I can't add them through the form on the site. I do not receive an error message, but the comments do not show up in the admin or the site. Also, even though the comments post from the admin screen, they do not show up on the site. Models.py class Beets(models.Model): content = models.TextField(max_length=240) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='likes') def __str__(self): return f"Beet by {self.author}" def get_absolute_url(self): return reverse('beets:beets-detail', kwargs={'pk': self.pk}) @property def total_likes(self): """ Likes for the beet :return: Integer: Likes for the company """ return self.likes.count() def likes_as_flat_user_id_list(self): return self.likes.values_list('id', flat=True) class Comment(models.Model): beet = models.ForeignKey( Beets, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=240) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.content views.py - just the comment part def add_comment_to_beet(request, id): if request.method … -
Django not saving timezone info. How to store this correctly
I've got this code in an ajax view: now = pytz.timezone("America/Guayaquil").localize(datetime.now()) print("HOUR: %s" % now.hour) new_timer = WorkTime.objects.create(inicio=now) print("new_timer.id: %s" % new_timer.id) print("new_timer.hour %s" % new_timer.inicio.hour) it prints this: HOUR: 18 new_timer.id: 16 new_timer.hour 18 "inicio" is a DateTimeField. Then I access the same object from a regular view to render an html, this is the code: last_timer = TiempoEmpresarial.objects.filter(final__isnull=True).last() print("Timer object:") print(last_timer.id) # is it the same obj? print(last_timer.inicio.hour) it prints this: Timer object: 16 23 It is the same object, id=16. But it has a different hour. Why?