Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirect to referer after post in CreateView in django
I have defined a CreateView in django I want to redirect to the referer of that view if that referer contants ‘center’. The idea is like “iredirect the page that brought you to the CreateView if that page’s path contains ‘center’” I am trying with the following code but is not working since self.request.META.get('HTTP_REFERER') is returning the path of the same createView class CompanyCreateView(LoginRequiredMixin, CreateView): model = CompanyModel context_object_name = 'company' template_name = 'riesgo/company/company_form.html' form_class = CompanyForm def get_success_url(self): if self.request.method == 'POST' and "_continue" in self.request.POST: return reverse('riesgo:company_update', kwargs={'pk': self.object.id}) elif 'center' self.request.META.get('HTTP_REFERER','/'): # here I want to redirect to page that brought you to the createview of the company else: return reverse_lazy("riesgo:company_detail", kwargs={"pk":self.object.id}) -
Using relay mutate_and_get_payload when using graphene-file-upload library
Currently, I am working on a project where we use relay for all views. In one of the views, we are to upload a file and we are using graphene-file-upload which uses graphene.Mutation mutate(). My question is there a way we can use relay mutate_and_get_payload()? I have tried bu failed at the moment -
How do I eliminate Unique Constraint failure in django?
Based on this, I'd like to get a clarification here. How would I ensure that editing/updating the teacher details does not create anew user with the same details??? I think this is the case when I attempt to update/edit an already saved teacher. Please help me out. The teacher model. class TeacherData(models.Model): id = models.AutoField(primary_key=True) teacher_user = models.OneToOneField(User, on_delete=models.CASCADE,null=True,blank=True) school = models.ForeignKey(School,on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) code = models.IntegerField(unique=True) email = models.EmailField() phone = models.IntegerField() def save(self, *args, **kwargs): self.user = User.objects.create_user(username=self.first_name,password=str(self.code),is_teacher = True,is_student = False,school_id=self.school.id) self.user.save() # mandatory as create_user is not recognized as save operation super().save(*args, **kwargs) The user model. class User(AbstractUser): school = models.ForeignKey(School, on_delete=models.DO_NOTHING, null=True, blank=True) #role = models.CharField(max_length=10, choices=ROLES, blank=False, null=False) is_student = models.BooleanField(default=True) is_teacher = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) The traceback. Traceback (most recent call last): File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\mixins.py", line 52, in … -
Javascript/Jquery toggle id with multiple variable
this is my first question, so apologies if not written clearly. I want to dynamically toggle a comment form after reply button is pressed. There are multiple comments (in below example three) to which a form (with different id) can be rendered separately. I am able to do this with static id for form but not with dynamically defined id... I have tried this static approach and this works fine. var functs_t = {}; functs_t['fun_27'] = $('#reply_comment_id_27').click(function() {$('#form_comment_id_27').toggle('slow');}); functs_t['fun_23'] = $('#reply_comment_id_23').click(function() {$('#form_comment_id_23').toggle('slow');}); functs_t['fun_21'] = $('#reply_comment_id_21').click(function() {$('#form_comment_id_21').toggle('slow');}); However, I am having struggling with a dynamic approach. var i; var functs = {}; for (i=0; i<comment_qs_id_list.length; i++) { var comment_id = comment_qs_id_list[i].toString(); var reply_comment_id = 'reply_comment_id_'+ comment_id; var form_comment_id = $('#'+reply_comment_id).attr('name'); // works >>> toggles comment 27 functs['func_reply_comment_'+comment_qs_id_list[i]] = $('#reply_comment_id_'+comment_qs_id_list[i]).click(function() {$('#'+'form_comment_id_27').toggle('slow');}); // does not work //functs['func_reply_comment_'+comment_qs_id_list[i]] = $('#reply_comment_id_'+comment_qs_id_list[i]).click(function() {$('#'+form_comment_id).toggle('slow');}); // works >> toggles everything (but what I want is to hide initially and only toggle after clicking reply button) //$('#'+form_comment_id).toggle('slow'); }; Thanks so much! -
Exception Value: 'User' object has no attribute 'update' thrown in DJANGO ORM
I couldn't figure what is wrong with below statement , I am getting 'User' object has no attribute 'update' thrown in DJANGO ORM if "device_id" in request_data: try: User.objects.get(device_id=request_data["device_id"]).update(device_id=None) except ObjectDoesNotExist: pass -
How to add GST calculation in Django oscar
I want to add GST calculations in django oscar. I need help on this as i am new to django oscar. please guide. -
npm run cannot find module webpack.js
im currently on a djangoRest and React course. I have experience on npm and python but this error is something i can't solve. Everithing went well until i "npm run dev" package.json file { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.13.16", "@babel/preset-env": "^7.13.15", "@babel/preset-react": "^7.13.13", "babel-loader": "^8.2.2", "react": "^17.0.2", "react-dom": "^17.0.2", "webpack": "^5.34.0", "webpack-cli": "^4.6.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.13.0", "@material-ui/core": "^4.11.3", "@material-ui/icons": "^4.11.2", "react-router-dom": "^5.2.0" } } webpack.config.js file const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { // This has effect on the react lib size NODE_ENV: JSON.stringify("production"), }, }), ], }; Error npm run dev > frontend@1.0.0 dev E:\Programacion cursos\Harvard\React&JavaScript\VsCode\react_django\frontend > webpack --mode development --watch "JavaScript\VsCode\react_django\frontend\node_modules\.bin\" no se reconoce como un comando interno o externo, programa o archivo por lotes ejecutable. internal/modules/cjs/loader.js:883 throw err; ^ Error: Cannot find module 'E:\Programacion cursos\Harvard\webpack\bin\webpack.js' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) … -
Enabling live restore on docker is giving OperationalError at [my-endpoint] could not translate host name "db" to address
I try to enable live restore following the official docs, just edit /etc/docker/daemon.json and reload docker daemon. When I check with docker info, it's showing Live Restore Enabled: true. So I think live restore is enabled. However, when I kill docker service by sudo systemctl stop docker and visit my Django app, it's giving an error, OperationalError at /product/69/ could not translate host name "db" to address: Temporary failure in name resolution Look like it cannot connect to the db. Before killing the docker service, it was working well. I didn't change my docker-compose.yml file. Did I miss anything? What did I dowrong? Here is the content: version: '3.7' services: db: image: postgres:12.4-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_DB=${SQL_DATABASE} - POSTGRES_USER=${SQL_USER} - POSTGRES_PASSWORD=${SQL_PASSWORD} web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code - ./static:/static/ expose: - 8000 depends_on: - db env_file: - ./.env nginx: restart: always build: ./nginx volumes: - ./static:/static/ ports: - "80:80" - "443:80" depends_on: - web -
How to get total duration in Django
I am trying to display duration time for an particular work. class UserData(models.Model): uid = models.CharField(max_length=100) email = models.CharField(max_length=100) start_date = models.DateField(auto_now_add=True,editable=False) end_date = models.DateTimeField(auto_now=True) @property def duration(self): if not (self.start_date and self.end_date): return None a,b=self.start_date, self.end_date return '%s:%s' % ((b-a).days*24 + (b-a).seconds//3600, (b-a).seconds%3600//60) But while i call duration property for getting total time, it's give unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date' error. How can i get the duration date please from my UserData model? -
posting with ajax within a ajax get method in django
i have a complain box which shows messages from users to admin .. this messages are coming through ajax get request so that it looks real time now i want to send back reply clicking on that reply button with a modal showing message input by default the reply button will add the receiver id while clicking on reply but i am stuck let me show you models.py class Message(models.Model): sender = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user') receiver = models.ForeignKey(User,on_delete=models.CASCADE,related_name='to_user') msg = models.CharField(max_length=1000,blank=True,null=True) sent = models.DateTimeField(auto_now_add=True) mark_as_read = models.BooleanField(default=False) def __str__(self): return self.sender.username + ' messaged ' + self.receiver.username views.py def reply_to_complains(request,id): url = request.META.get('HTTP_REFERER') my_id = request.user.id if request.method == 'POST': msg = request.POST.get('msg') Message.objects.create( receiver_id=id, sender_id=my_id, msg=msg, ) return HttpResponseRedirect(url) form <form method="post" action="{%url 'reply_to_complains' id%}"> {% csrf_token %} <div class="form-group"> <label for="message-text" class="col-form-label">Message:</label> <textarea id="msg_by_admin" name="msg" placeholder="type here .." required></textarea> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Send message</button> </div> </form> ajax get <script> setInterval(function () { $.ajax({ method: "GET", url: "get_complains", success: function (data) { console.log(data) $("#msg").empty(); $.each(data, function (key, value) { var a = value.Sender.charAt(0).toUpperCase() + value.Sender.slice(1); var b = value.Msg; var c = value.Sent.substring(0, 10) var Read = value.Read; console.log(Read) this line ---> var … -
PyCharm 2021.1 Community Edition auto import Django CASCADE
I upgraded PyCharm Community Edition to 2021.1 a few days ago. But I found it can't resolve some Django auto import correctly now. For example, I set CASCADE as on_delete for one ForeignKey, it should suggest me to import django.db.models.CASCADE, but it suggest tkinter.CASCADE instead. -
Using Fetch with Javascript and Django
I am new to Javascript and I am using Django. I've read documentation about the Javascript fetch API but I'm confused about something - if anyone can explain it I'd really appreciate it. I've seen code that didn't include a url for the API. Where is this coming from within the framework - when I write code, how do I know what to put right after the fetch part? Example: const load_like = (post, postLikes, likePost, current_user) => { const csrftoken = getCookie('csrftoken'); fetch(`/post/${post.id}`, { method: 'PUT', body: JSON.stringify({ likes: [post.original_poster.id] }), headers: { "X-CSRFToken": csrftoken } }) .then(response => response.json()) .then(data => { display_likes(data, postLikes, likePost, current_user) }) } Is this done in urls.py ? For example would it be: path("post/<int:post_id>", views.post, name="post" ), I want to make sure I understand how to write this type of line and understand why these parts should go here: fetch(`/post/${post.id} -
What is the best approach to deploy nextjs project to google app engine standard environment?
I have created nextjs project with Isomorphic admin theme -
Python Inheritance with unique attribute in master class
I'm with a little problem. class Person(models.Model): cpf = BRCPFField(unique=true) class Student(Person): new_field = .... class Teacher(Student): another_field = ... class BoardMember(Person): class Meta: proxy = True CPF = USA SSN. A person can be a student, a board member and a student can be a teacher in future. When I register a person with a cpf, it's ok. But when I try to register the same person as a student, python show me a error because of the unique field. How can I solve this? -
How to post a Pandas DataFrame using API in Django
Currently I send one post request per DataFrame's row, which means that I read the row, convert it to Json data and send it using request.post. Is there any better way to send the entire data frame in one post request? Thanks, -
django saving two model in a one to many relationship
I trying to save two model in a one to many relationships but I am getting the error NOT NULL constraint failed:domestic_banks_naturalperson.domesticbank_id model # Create your models here class DomesticBank(models.Model): bank_name = models.CharField(max_length=100, null=True) subsidiary_or_branch = models.CharField(max_length=100, null=True) home_country = models.TextField(max_length=500, null=True) publish_date = models.DateField('Date Published', null=True) def __str__(self): return self.bank_name class NaturalPerson(models.Model): domesticbank = models.ForeignKey(DomesticBank, on_delete=models.CASCADE) natural_person_name = models.CharField(max_length=100, null=True) country = models.CharField(max_length=100, null=True) upload_passport_copy = models.FileField(upload_to='Passport/PDF', null=True) upload_additional_ID = models.FileField(upload_to='Other_ID/PDF', null=True) def __str__(self): return self.natural_person_name def add_bank_form(request): if request.method == 'POST': form = BankForm(request.POST) natural_person_form = NaturalPpersonPform(request.POST,request.FILES) OwnShares = OwnSharesInOtherCompanyForm(request.POST, request.FILES) if form.is_valid() and natural_person_form.is_valid(): form = form.save() naturalperson = natural_person_form.save(commit=False) naturalperson.form = form naturalperson.save() return HttpResponseRedirect('/DisplayBankRisk') else: form = BankForm() natural_person_form = NaturalPpersonPform() return render(request, 'add_domestic_bank.html', locals()) -
Django and hvad - deep query on translatable field
I have two models: Diet Product Diet has a foreign key that references Product. Product has a translatable field called name. I'd like to perform this query: Diet.objects.language().get(product__name='Some name') However, the following error occurs: WrongManager at /alimentazione-vie-urinarie Accessing translated fields like product.name from an regular model requires a translation-aware queryset, obtained with the .language() method. For regular, non-translatable models, you can get one using hvad.utils.get_translation_aware_manager I found an old similar question, however the answer hasn't worked for me. -
Adding Context to Django View Causing My Highcharts Map to Disappear
This is my first Django project, and I am working on a Django html template that should contain a Chart.JS bar graph (https://www.chartjs.org/docs/latest/charts/bar.html) alongside a Highcharts drilldown map of the US (https://www.highcharts.com/demo/maps/map-drilldown). I've successfully implemented my Chart.JS bar graph and passed data to it from our AWS RDS. But now when I try to implement even just the stock Highcharts code from their website, the chart fails to render at all. After trying to isolate the problem, I've found that the map does render if I delete "context" from the return statement in my view (i.e. delete "context" from the final line in my first block of code below). But this obviously then inhibits my bar graph from rendering, and I've been unable to fix it such that both graphs render. Any help would be greatly appreciated! My Django View: def index(request): mydb = mysql.connector.connect( host=xxxx, user=xxxx, password=xxxx, database=xxxx ) mycursor = mydb.cursor() mycursor.execute("WITH CS1 AS (SELECT cts.Name, cts.State, m.Frequently, m.Always FROM Masks m JOIN Counties cts ON (m.FIPS = cts.FIPS)) SELECT CS1.State, AVG((CS1.Frequently+CS1.Always)*100) AS Perc_High_Frequency FROM CS1 WHERE CS1.State<>'Puerto Rico' GROUP BY CS1.State ORDER BY Perc_High_Frequency DESC") tempList = mycursor.fetchall() statesMaskName = [item[0] for item in tempList] statesMaskPerc = … -
Django: Is there any performance differences when using ajax?
I'm working on refactoring project in the middle of the work. There are a lot of context when view return render. I want to change it to get response when dom rendered using ajax. I know it makes more request, but I wondered if there are any performance differences. If not, I want to do that. -
AttributeError: 'NoneType' object has no attribute 'distinct'
I have the below table view CREATE VIEW vStaff AS SELECT ContactInfo .*, Staff.position FROM ContactInfo LEFT JOIN Staff ON Staff.name = ContactInfo.name that selects information from these two models class ContactInfo(models.Model): name = models.CharField(max_length=30) email = models.EmailField(max_length=30) address = models.CharField(max_length=30) class Staff(models.Model): name = models.CharField(max_length=30) position = models.CharField(max_length=30) However, when I try to select from the vStaff like below in modelAdmin I get the above error Staff.objects.annotate(val=RawSQL("select * vStaff", ())) AttributeError: 'NoneType' object has no attribute 'distinct' -
How can I show a div or html element after submitting a form and retrieve some information from a view in Django
Currently when the user introduces a string in an input field and clicks the submit button, this invokes a view that returns through return render(request, 'index.html', context) a context that it basically contains data that is displayed in a table. I would like said table to be visible only after submitting the form and not before and that when it is visible it shows the information obtained from the view. The problem is that if through inline styling I make this table not visible, for example in the following way: <div class="row" id="searchVariantTable" style="display: none;"> <!-- SOME TABLE HERE--> </div> And then I use the onsubmit event for form or onclick for button, it doesn't work. (It works partially, I can see the tbody but thead is missing, so basically I can't display the retrieved data from the database). Similarly, if I try something like this: $('document').ready(function() { $('#searchVariantTable').hide(); $('form').submit(function(e) { $('#searchVariantTable').show(); e.preventDefault(); }); }); It doesn't work either. I think the last option, if I'm not mistaken, is AJAX, but I'm not quite sure how to do something like that with Django (it's my first time using Django) What am I doing wrong? Is there an option that I … -
Page Not Found (404) using Django (first app)
I'm working on my first django app, and i'm a rookie at coding, sometimes i really dont get where is the error and the tutorials and documentation dont help me either. The error is this one: Error Now, the code i have for the views: def update(request, id): cliente = get_object_or_404(Cliente, id=id) if request.method == 'GET': form = clienteForm(instance=cliente) return redirect("/clientepag/", id=id) else: form = clienteForm(request.POST, instance=cliente) if form.is_valid(): form.save() return redirect("/clientepag/", id=id) else: form = clienteForm() return redirect("/clientepag/", id=id) def clientepag(request, id): cliente = Cliente.objects.get(id=id) return render(request, 'clientepag.html', {'cliente': cliente}) I'm trying to make my update function to redirect me to clientepag/id, but i dont get why my clientepag function isnt getting the id i'm sending from the update, the db is being updated, i validated that, but the clientepag isnt getting the id i'm trying to send from the update, and i dont know if its the update that isnt sending the id, or the clientepag that isnt getting it, or is rejecting it. I already validated that the update function still have the id after the form.save() line My path list: from django.contrib import admin from django.urls import path from clientesapp import views urlpatterns = [ path('admin/', … -
Exporting and Importing a foreign key field that has a many-to-many relationship in Django
I've got a complicated relationship between my Django models and I'm trying to get django-import-export to play nicely. class Person(models.Model): name = models.CharField(max_length=64) class Team(models.Model): rep = models.ManyToManyField(Person, related_name="rep") def get_reps(self): return "/".join(sorted([p.name for p in self.reps.all()])) class Account(models.Model): tid = models.IntegerField("Territory ID", primary_key=True) name = models.CharField("Territory Name", max_length=64) sales_team = models.ForeignKey(Team, related_name="sales_team") I'm trying to export (and hopefully later import) the territories with the names of the reps as rendered by the get_reps method. class TerritoryResource(resources.ModelResource): tid = fields.Field(attribute='tid', column_name="Territory ID") name = fields.Field(attribute='name', column_name="Territory Name") sales_team = fields.Field( column_name="Sales Team", widget=widgets.ForeignKeyWidget(Team, "get_reps") ) The export is giving me a blank field. If I don't use the widget I get the Team ID as I'd expect. Is it possible to get my custom name in the export? -
An error in my relation, violates unique constraint
I'm working on a small project using Django, A task can be only in one status, The Error i get : duplicate key value violates unique constraint "task_task_status_id_de4e8cac_uniq" DETAIL: Key (status_id)=(1) already exists. What kind of relationship must I do between the two models? This is my models : class Task(models.Model): status = models.ForeignKey(Status, related_name="tasks", on_delete=models.CASCADE) title = models.CharField(max_length=60, blank=False, null=False) class Status(models.Model): title = models.CharField(blank=False, null=False, max_length=255) slug = models.CharField(blank=False, null=False, max_length=255) order = models.SmallIntegerField(default=0) def __str__(self): return self.title -
Django and Apache Server Configuration
I implemented a Django project with MySQL backend. It runs well using "Python manage.py runserver." Apache seems installed well with no errors. I can access the default apache server. However, I couldn't make the apache web server and Django work together. I followed the link below. https://studygyaan.com/django/how-to-setup-django-applications-with-apache-and-mod-wsgi-on-ubuntu I edited 000-default.conf and djangoproject.conf on the server. Could you give me some advice where I should look into? Version information. Python: 3.8.5 Django: 3.0 Ubnutu: 20.04 When I run "sudo systemctl status apache2" ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2021-04-14 17:18:03 UTC; 6 days ago Docs: https://httpd.apache.org/docs/2.4/ Main PID: ****(apache2) Tasks: ** (limit: **) Memory: M CGroup: /system.slice/apache2.service ├─ **** /usr/sbin/apache2 -k start ├─ /usr/sbin/apache2 -k start └─ /usr/sbin/apache2 -k start