Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: Cannot assign object must be a instance
I have been trying to register a ClienteNatural, which has two foreign keys, one of Correo and another of Lugar. When making the query in the database to pass the Correo object to the ClienteNatural, I get this error, if someone can help me. Thank you. Momentarily I put a fixed value to Lugar just to test, then I will make it dynamic, but that Lugar object that I assign to fk_lugar doesn't generate an error, just fk_correo. Error: *** ValueError: Cannot assign "'Correo object (22)'": "ClienteNatural.fk_correo" must be a "Correo" instance. Models.py class ClienteNatural(models.Model): rif = models.CharField(primary_key=True, max_length=12) carnet_id = models.IntegerField(blank=True, null=True) complemento_direccion = models.CharField(max_length=25) puntos_disponibles = models.IntegerField(blank=True, null=True) cedula = models.CharField(max_length=12) primer_nombre = models.CharField(max_length=12) segundo_nombre = models.CharField(max_length=12, blank=True, null=True) primer_apellido = models.CharField(max_length=12) segundo_apellido = models.CharField(max_length=12) fk_lugar = models.ForeignKey('Lugar', db_column='fk_lugar', on_delete=models.CASCADE) fk_correo = models.ForeignKey('Correo', db_column='fk_correo', on_delete=models.CASCADE) class Meta: managed = False db_table = 'cliente_natural' class Correo(models.Model): codigo = models.AutoField(primary_key=True) usuario = models.CharField(unique=True, max_length=30) class Meta: managed = False db_table = 'correo' class Lugar(models.Model): codigo = models.AutoField(primary_key=True) nombre = models.CharField(max_length=50) tipo = models.CharField(max_length=50) fk_lugar = models.ForeignKey('self', models.DO_NOTHING, db_column='fk_lugar', blank=True, null=True) class Meta: managed = False db_table = 'lugar' forms.py class Cliente_Natural_Form(forms.ModelForm): rif = forms.CharField(max_length=12, required=True) carnet_id = forms.IntegerField complemento_direccion = … -
Django: looping through filtered list in template
I have an html template where I would like to loop through objects in a model (SpeciesPage) which are filtered by a certain field value (subfamily_name="Pierinae") and display them in a list. The filtered results span multiple foreign key relationships. Ultimately, I want the template to loop through and display multiple filtered results in separate lists, but I cannot get anything to render looping through one filtered list. I feel like what I'm trying to accomplish should be simple. models.py (abbreviated to show only relevant fields) class Subfamily(models.Model): subfamily_name = models.CharField(max_length=200) class Tribe(models.Model): subfamily = models.ForeignKey(Subfamily, on_delete=models.SET_NULL, null=True) tribe_name = models.CharField(max_length=200) class Genus(models.Model): tribe = models.ForeignKey(Tribe, on_delete=models.SET_NULL, null=True) genus_name = models.CharField(max_length=200) class Species(models.Model): genus = models.ForeignKey(Genus, on_delete=models.SET_NULL, null=True) species_name = models.CharField(max_length=200) species_page = models.OneToOneField('SpeciesPage', on_delete=models.SET_NULL, null=True) class SpeciesPage(models.Model): title = models.CharField(max_length=100, primary_key=True) species_name = models.OneToOneField(Species, on_delete=models.SET_NULL, null=True) views.py class SpeciesPageListView(generic.ListView): model = SpeciesPage template_name = 'speciespage_list.html' def show(request): pierinae_pages = SpeciesPage.objects.filter(species_name__genus__tribe__subfamily__subfamily_name="Pierinae") context = { 'pierinae_pages': pierinae_pages, } return render(request, 'speciespage_list.html', context=context) speciespage_list.html ... {% for speciespage in pierinae_pages %} <tr> <td><i>{{ speciespage.title }}</i></td> ... </tr> {% endfor %} ... I used the following answers from here in an attempt to solve my problem: Cannot use filter inside Django template html … -
How to import dbpedia data into arangodb for use in a django website?
I'm new to programming and just learnt python and some django basics. I want to build a website to display wikipedia data in a particular format and also display the connections using plotly dash. However i'm unable to find instructions on how to import dbpedia data into arango db so as to store objects/entities as documents with attributes and map the graph of relationships. Something like relfinder on dbpedia website, offering more info along with it. Is it possible to first setup arango db in django and then use sparql querying with python to build my own dataset according to requirements? If yes, please provide some instructions or link some resources with info on how to do it. Is there any other way I could achieve this in an easier way? -
DateInput - Enter a valid date
I have a form field that I want to have as a calendar widget that defaults to the current date. I had it so it was showing the date in d/m/y format but when I'd submit it would say Enter a valid date forms.py class CreateBlogPostForm(forms.ModelForm): published = forms.DateField() class Meta: model = BlogPost fields = ('title', 'published','featured_image', 'post',) widgets = { 'title': forms.TextInput(attrs={'class': 'testimonial-name-field', 'placeholder': 'Title'}), 'published': forms.DateInput(format=('%d-%m-%Y'), attrs={"type": 'date'}), 'post': forms.TextInput(attrs={'class': 'blog-post-field', 'placeholder': 'Write something..'}), } models.py class BlogPost(models.Model): title = models.CharField(max_length=100) published = models.DateField() featured_image = models.ImageField(upload_to='blog/%Y/%m/%d') post = models.TextField() slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Blog" def __str__(self): return self.title create-blog.html {% extends 'base.html' %} {% block content %} <div class="container text-center"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form.title}} {{form.post}} {{form.featured_image}} {{form.published}} {{form.errors}} <button type="submit" class="btn btn-primary"><i class="fa fa-plus" aria-hidden="true"></i> Submit</button> </form> </div> {% endblock content %} -
Angular Routing structure for Webshop with Filter
Im working on a Angular Webshop with Django Backend. I filter the articles by multiple parameters like brand,Color, gender or category. To avoid nasty hardcoding and URLs I tried Angular routing, where I used query parameters at the end of the URL for each filter option. But there are many variations, because of the filters the user can pick. So I‘m searching for a better way to solve this issue. The main Idea was a structure like „www.example.com/Gender/Brand/Category...“. But because the user can choose the filter individually, the Routing Params from Angular wouldn’t be clearly associated to a single filter option (first path wouldn’t be Gender if the user just picks the filter „Adidas“ -> URL: www.example.com/Adidas“). So how can I associate the Routing Param with a variable to pass it to the Django Filter ? import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {HttpClientModule} from '@angular/common/http'; import {RouterModule} from '@angular/router'; import {AppComponent} from './app.component'; import {HomepageComponent} from './home/homepage.component'; @NgModule({ declarations: [ AppComponent, HomepageComponent ], imports: [ BrowserModule, HttpClientModule, RouterModule. Module.forRoot([ {path: 'home', component: HomepageComponent}, {path:':param1', component: filteredListCompoment }, {path:':param1/:param2', component: filteredListCompoment}, {path:':param1/:param2/ :param3', component: filteredListCompoment}, {path: '**', redirectTo: '', pathMatch: 'full'} ]), ], bootstrap: [AppComponent] }) export class … -
Should I use Generic Relations or One To One?
I'm making a social media website and I'm currently coding the comments, different types of posts and reports (the models). I read that when using Generic Relations, the ORM would use N queries to get all the related content. I know this can be quit hard on runtimes and memory, so should I use One To One fields instead of Generic Relations? Someone on another post said to not prematurely optimize your site, but it couldn't hurt to do what you can for optimization so there are less updates later right? Side question, could I further optimize the site (say when a user is looking at a post) by querying for a few comments and only load more when the user clicks the 'load more' button? -
StaticLiveServerTestCase log in not working
I am currently trying to conduct functional testing on my django website using the StaticLiveServerTestCase. However, I cannot get passed my login page. It says that my username and password are incorrect, which leads me to believe that I am saving my user incorrectly. My test case is down below. I have seen several post regarding a login issue but none of them have helped my situation. Please let me know if you have any advice for how to correct this. class EmpTest(StaticLiveServerTestCase): def setUp(self): self.selenium = WebDriver() self.emp = User.objects.create(username='testuser0', password='password') self.emp.save() def tearDown(self): self.selenium.close() def test_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/accounts/login/')) username_input = self.selenium.find_element_by_id("id_username") username_input.clear() username_input.send_keys(self.emp.username) password_input = self.selenium.find_element_by_id("id_password") password_input.clear() password_input.send_keys(self.emp.password) self.selenium.find_element_by_xpath('//button[text()="Log in"]').click() time.sleep(15) -
Find Unique Value and attach all related values in Array of Objects
I want to create an array of objects. I have all the variables and need to just format all the values. These are my values: url = "Goodreads", search = "Fantasy", search_res = [ { "book": "Harry Potter", "rating": "10.0" }, { "book": "Lord of The Rings", "rating": "9.0" } ] url = "GoodReads", search = "Dystopia", search_res = [ { "book": "Handmaids Tale", "rating": "9.0" }, { "book": "Divergent Series", "rating": "8.5" } ] url = "Kindle", search = "Fantasy", search_res = [ { "book": "Twilight Series", "rating": "5.5" }, { "book": "A Discovery of Witches", "rating": "8.5" } ] url = "Kindle", search = "Dystopia", search_res = [ { "book": "Hunger Games", "rating": "9.5" }, { "book": "Maze Runner", "rating": "6.0" } ] My code: assign_url = url the_list = [] urls = { 'the_url' : assign_url, 'results' : [] } data['search'] = search data['results'] = search_res urls['results'].append(data) the_list.append(urls) pprint(json.dumps(the_list)) My Result: ('[{"the_url": "GoodReads", "results": [{"search": "Fantasy", ''"results": [{"book": "Harry Potter", "Rating": "10.0"}, {"book": "Lord of The Rings", "Rating": "9.0"}]}]}]') ('[{"the_url": "GoodReads", "results": [{"search": "Dystopia", ''"results": [{"book": "Handmaids Tale", "Rating": "9.0"}, {"book": "Divergent Series", "Rating": "8.5"}]}]}]') ('[{"the_url": "Kindle", "results": [{"search": "Fantasy", ''"results": [{"book": "Twilight Series", "Rating": "5.5"}, {"book": … -
Duplicate Values with Foreign Key in Django Model
So I have a few models in my django app that look like this: class WHID(models.Model): whid = models.CharField(max_length=8) class Department(models.Model): name = models.CharField(max_length=50) whid = models.ForeignKey(WHID, on_delete=models.CASCADE) I want to have it so that I can't create a duplicate Department name for each WHID. So if I have two entries in the WHID table: id whid 1 whid1 2 whid2 Then in the Department table: name whid Department1 1 Department1 2 Department1 1 <----How do I stop this record from being created Any help is appreciated. Thank you. -
Connect Django Model to a single existing database table
I need to connect a Django Model to an existing database table. My model looks as below, and I made sure the fields in the model match the DB table class Mytable(models.Model): fld1 = models.CharField(max_length=100) fld2 = models.FloatField(max_length=3000, null=True) fld3 = models.FloatField(max_length=3000, null=True) fld4 = models.FloatField(max_length=3000, null=True) fld5 = models.DateTimeField() fld6 = models.CharField(max_length=100, null=True) class Meta: managed = False db_table = 'schema.Mytable' the user I defined in settings.py is a read only user. fld1 is the primary key (PK) ... there is no FK. When I start the app .... I get this error: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-01031: insufficient privileges) It appears to me that Django is trying to create a new table in the schema .... but there is not user privilages for DLL, by design. Please advise what am I doing wrong, and potential changes needed to allow Django to access an existing table in the specified schema. -
Need Good Python Courses and Study material
I am quite new to Programming, with past few experience in JAVA,Now looking forward to learn Python, Please suggest some really good and interactive courses and Study Materials that I could follow along.The aim is to go from Scratch to be able to tackle some Data structures problems. -
Can't handle exceptions in requests
For some reason I can't handle exceptions using requests library at all. Here's my code: import requests p = open('file.txt', 'r') ls = p.readlines() while True: c = 0 ps = {'http': ls[c].replace('\n', '')} r = requests.get('targeturl', proxies=ps, timeout = 10) if r: try: print('Success.') w = open('savefile.txt', 'w') w.write(ls[c]) c += 1 except Exception: print("Failure.") continue # OR except: print('Failure.') continue The purpose of my code is to check the proxy list on the targeturl, and save the working ones into a file. Those except statements should just print 'Failure.' and continue, but they don't. I always get the same errors every time. I even tried handling literally every error I see, still get the same problem. except requests.exceptions.HTTPError as errh: print ("Http Error:",errh) except requests.exceptions.ConnectionError as errc: print ("Error Connecting:",errc) except requests.exceptions.Timeout as errt: print ("Timeout Error:",errt) except requests.exceptions.RequestException as err: print ("OOps: Something Else",err) Here's what I always get: Traceback (most recent call last): File "C:\Users\mon-pc\AppData\Roaming\Python\Python36\site-packages\requests\packages\urllib3\connection.py", line 138, in _new_conn (self.host, self.port), self.timeout, **extra_kw) File "C:\Users\mon-pc\AppData\Roaming\Python\Python36\site-packages\requests\packages\urllib3\util\connection.py", line 98, in create_connection raise err File "C:\Users\mon-pc\AppData\Roaming\Python\Python36\site-packages\requests\packages\urllib3\util\connection.py", line 88, in create_connection sock.connect(sa) socket.timeout: timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File … -
I want to parse and upload a large csv file into a msql database, but its taking forever. Python/Django
def process_data(self): f = io.TextIOWrapper(self.cleaned_data['data_file'].file, encoding='utf-8-sig') reader = csv.DictReader(f) for row in reader: Csv.objects.create(starttime=datetime.strptime(row["startTime"], '%Y-%m-%d %H:%M:%S'), incidents_id=(row['id']), type=(row['type']), subtype=(row['subtype']), reportdescription=(row['reportDescription']), street=(row['street']), reportby=(row['reportBy']), longitude=Decimal(row['longitude']), latitude=Decimal(row['Latitude']), endtime=datetime.strptime(row["endTime"], '%Y-%m-%d %H:%M:%S'), dataowner_id=1) -
Django Webpack Loader setting does not render images
I am using Django webpack loader to render VueJs files. I have two similar applications and I can view the images in one application but other does not work. This is how I configure my Vue Webpack: const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config.module.rules.delete('eslint'); config.optimization .splitChunks(false) config.module .rule('vue') .use('vue-loader') .loader('vue-loader') .tap(options => { options.transformAssetUrls = { img: 'src', image: 'xlink:href', 'b-img': 'src', 'b-img-lazy': ['src', 'blank-src'], 'b-card': 'img-src', 'b-card-img': 'src', 'b-card-img-lazy': ['src', 'blank-src'], 'b-carousel-slide': 'img-src', 'b-embed': 'src' } return options }) config .plugin('BundleTracker') .use(BundleTracker, [{filename: '../frontend/webpack-stats.json'}]) config.resolve.alias .set('__STATIC__', 'static') config.devServer .public('http://0.0.0.0:8080') .host('0.0.0.0') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .headers({"Access-Control-Allow-Origin": ["\*"]}) } }; These are my Django settings: WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': DEBUG, 'BUNDLE_DIR_NAME': '/bundles/', # must end with slash 'STATS_FILE': os.path.join(FRONTEND_DIR, 'webpack-stats.json'), } } MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") and urls.py: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have been struggling for two days. I can get the url as text in the template, meanwhile images are not rendered as image. Anyone has a clue ? Thanks -
Get all users which passed the exam
I need help in django queries. I have ExamResult model which keep results of exam. How get all users which passed the exam and are in the same study group. ExamResult model class ExamResult(Model): exam = ForeignKey(Exam, blank=False, null=False, on_delete=CASCADE) score = IntegerField() user = ForeignKey('Accounts.UserAccount', blank=False, null=False, on_delete=CASCADE, ) exam_date = DateTimeField(auto_now_add=True, blank=False, null=False) StudyGroup model class StudyGroup(models.Model): group_name = models.CharField(max_length=10, blank=False, null=False) -
Django - One to Many Single Query on Same Table - Get Most Recent and Oldest on Group By
Suppose I have the following: from django.db import models class Book(models.Model): name = models.CharField(max_length=300) price = models.DecimalField(max_digits=10, decimal_places=2) class Customer(models.Model): name = models.CharField(max_length=300) class Sale(models.Model): date = # Some date or insertion time stamp payment_method = models.CharField(max_length=300) book = models.ForeignKey(Book, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) ---------- I've searched through many forums and the Django docs but I'm still a bit confused. If I want to have a query for all books, but also include the name of the first and last customer that purchased a said book with said payment method, how would I accomplish this? Where the SQL equivalent of the joins would be: SELECT a.name as book_name, a.price as book_price -- More selects on individual customer names or sale payment methods FROM Book a LEFT JOIN ( SELECT first_sale.* FROM Sale first_sale WHERE date = ( SELECT MIN(date) FROM Sale c WHERE b.id = c.id ) ) b ON b.book = a.name -- Some kind of join LEFT JOIN ( SELECT last_sale.* FROM Sale last_sale WHERE date = ( SELECT MAX(date) FROM Sale c WHERE b.id = c.id ) ) c ON c.book = a.name -- Some kind of join LEFT JOIN Customer d ON d.id = b.customer_id … -
Django djoser user registration with email confirmation
I'm using Django and djoser as backend for a mobile app. When I make following POST request: curl -X POST http://127.0.0.1:8000/auth/users/ --data 'username=myusername&email=myemail&password=mypwd' I receive an email to myemail with the activation link with the proper uid and token. Then I try to activate the user by doing: curl -X POST http://127.0.0.1/auth/users/activation/ --data 'uid=myuid&token=mytoken' After this I get a 404 NOT FOUND response. Djoser documentation says the activation endpoint is /users/activation/. My urls.py is as follows: from django.contrib import admin from django.urls import include, path, re_path urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('api.urls')), re_path(r'^auth/', include('djoser.urls')), ] Does anybody know what I'm doing wrong? Thank you so much for your support! -
How can i dynamically update the graph using Django-Ajax-Snowflake?
I'm trying to update the graph dynamically which gets values from the table and whenever the user changes/enters any value it should reflect in the graph automatically without having a refresh button. How to do that using Django-ajax-snowflake any suggestions to do that, definitely not in Dash. Here is the code for my table: <table id="" class=""> <thead> <tr> <th>Bump!</th> <th>C1</th> <th>C2</th> <th>C3</th> <th>NUMERATOR</th> <th>DENOMINATOR</th> </tr> </thead> <tbody> {% for x in measures %} <tr> <th> <input type="checkbox" id="" class=""> </th> <td> {{x.C1}} </td> <td>{{x.C2}}</td> <td>{{x.C3}}</td> <td><input class="" type="text" value="{{x.NUMERATOR}}"></td> <td><input class="" type="text" value="{{x.DENOMINATOR}}"></td> </tr> {%endfor%} </tbody> </table> -
How do I add link to another page [Django 3.0]? Reverse not found
I'm trying to add link (to blogDetails.html) to anchor on the main page and cannot do it (without Django it takes approximately 1,2 sec). index.html <a href="{% url 'blogDetails' %}">O blogu</a> urls.py path('blogDetails/', views.BlogDetailsPageView.as_view(), name='blogDetails'), views.py class BlogDetailsPageView(TemplateView): template_name = 'blog/blogDetails.html' Error I get: Reverse for 'blogDetails' not found. 'blogDetails' is not a valid view function or pattern name. What on earth is going on here? All help appreciated. -
Increment a variable within django template tags
I'm creating a registration form, where the user can pick multiple shirt sizes. There is a shirt model, in which one of the fields is a "quantity" of the quantity of the shirt size that the user wishes to purchase with their registration. If the user does not select any extra shirts, I want to print "No extra shirts." {% with totalshirts=0 %} {% for s in shirts %} {% if s.quantity > 0 %} <div class="flex"> <p class="confirm-text" style="width: 210px">{{ s.size.name }}:</p> <p class="confirm-text"><span class="txt-grey">{{ s.quantity }} shirt{{ s.quantity|pluralize }} | {{ event.extra_shirts_price | currency }}</span></p> </div> {% endif %} {{ totalshirts|add:s.quantity }} {% endfor %} {% if totalshirts == 0 %} <p class="footer-text">No extra shirts.</p> {% endif %} {% endwith %} I tried to increment the quantity each time the for loop is run, but it returns 0 unless the user selects the last shirt size (XXXL). The variable seems to default to 0 every time the loop is run. Here is an example of the output of this program Extra Shirts 0 Youth Large: 1 shirt | $10.00 1 0 Adult Medium: 1 shirt | $10.00 1 Adult Large: 1 shirt | $10.00 1 0 0 0 … -
Guardar multiples imágenes en django 2.2
no puedo guardar todas las imágenes que agrego en el formulario este es el código de las views Views models y este es el error que aparece enter image description here -
Django adding new attribute to WSGIRequest
Hey im kinda new to Django and the whole Views/Request process. So I noticed i got the auth_user inside the request object due to the User middleware I had inside the settings file, and anywhere i have the request, i can call the user object with request.user I kinda have a similar modal/object that is pretty important and I saw how to create a basic middleware but I'm not for sure how to replicate similar functionality where I'd be able to access that specific object inside the request like "request.object" -
checking the display of publications (tests)
in short: test lines: [..] print(self.post.created_at) # 2019-12-10 19:10:28.362152+00:00 print(timezone.now()) # 2019-12-10 19:10:28.517711+00:00 resp = self.client.get(reverse_lazy('posts:post_list')) self.assertIn(self.post, resp.context['posts']) assertIn is TRUE if in my views: queryset = Post.objects.filter() assertIn is FALSE if in my views: queryset = Post.objects.filter(created_at__lte=timezone.now()) # print(resp.context['posts']) shows nothing in tests In production all works well. If you have any idea why I get False, please let me know! Thanks! -
Django extension graph_models doesn't generate the characters
I ran a Django app on a Docker container, then ssh into it and pip install pydotplus and apk add graphviz, then I ran ./manage.py graph_models -a -g -o my_project_visualized.png. It generated a file with model and relationship. But all the characters render as squares, as if they are unicode or something. All my models are English, so should be within ascii range. -
BASH: Launching a server in the background
I have a Django AWS server that I need to keep running over the weekend for it to be graded. I typically start it from an SSH using PuTTY with: python manage.py runserver 0.0.0.0:8000 I was originally thinking of making a bash script to do the task of starting the server, monitoring it, and restarting it when needed using the but was told it wasn't going to work. Why?. 1) Start the server using python manage.py runserver 0.0.0.0:8000 & to send it to the background 2) After <some integer length 'x'> minutes of sleeping, check if the server isn't up using ss -tulw and grep the result for the port the server should be running on. 3) Based on the result from step (2), we either need to sleep for 'x' minutes again, or restart the server (and possibly fully-stop anything left running beforehand). Originally, I thought it was a pretty decent idea, as we can't always be monitoring the server. My partner looked at me in disbelief as if I said something silly, and I can't figure out why.