Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I export Qr code as an images to an excel export in Python and Django
I am trying to create a utility to export Qr code images to an excel file for tagging. I am using qrcode library to generate QR codes and openpyxl library to create the spreadsheet file. So far the spreadsheet export works great without the Qr code column however as soon as i add the code to add qr code to the excel column, my server crashes and stops without any verbose message. Below is my working code snippet without the qr code snippet: import openpyxl from openpyxl import Workbook from openpyxl.styles import Font, Alignment, Border, Side, PatternFill from openpyxl.utils import get_column_letter from openpyxl.styles.colors import BLACK def process_tagging_export(queryset): response = HttpResponse(content_type='application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet',) response['Content-Disposition'] = 'attachment; filename=QR_Code_Tags.xlsx' workbook = Workbook() workbook.remove(workbook.active) header_font = Font(name='Calibri', bold=True) centered_alignment = Alignment(horizontal='center') borders = Border(bottom=Side(border_style='medium', color='FF000000'),top=Side(border_style='medium', color='FF000000'),right=Side(border_style='medium', color='FF000000'),left=Side(border_style='medium', color='FF000000'),) wrapped_alignment = Alignment(vertical='top',wrap_text=True) columns = [ ('Asset Code', 30), ('Asset Name', 30), ] worksheet = workbook.create_sheet( title="QR Code Tags", index=1, ) row_num = 1 fill = PatternFill( start_color='b3b3b3', end_color='b3b3b3', fill_type='solid', ) for col_num, (column_title, column_width) in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title cell.font = header_font cell.border = borders cell.alignment = centered_alignment cell.fill = fill column_letter = get_column_letter(col_num) column_dimensions = worksheet.column_dimensions[column_letter] column_dimensions.width = column_width for item … -
How to add test data into django admin using a script
I am currently trying to create script where once the data has been deleted from django admin, we can add the data into database again for testing purposes. In django when we are adding data, we need to fill every field in django admin but what i want is a script in which I have some test data and when I run, it automatically adds it to the database without the need of django admin. How can I achieve this? -
Rrrule for reccurence
i am using dateutil module rrule ical (https://dateutil.readthedocs.io/en/stable/index.html) in Django for handling date related recurrence. my question is how we can calculate any indication that we give this number of occurrence already done and this number of recurrence remaining. Suppose a person created some recurrence visit in their home town. start date :-- 28/10/2022 freq:-- monthly end date:-30/12/2022 we have rrule count for calculating total number of visit. but my problem is that i want to calculate it dynamicaly like after 30/11/2022 i want some rule that give me the remaining visit :-1 and already done visit 2. thanks total_number_of_visit = rule.count() upcoming_visit = total_number_of_visit- ??? -
it's shows for each and every project - RemovedInDjango30Warning,
can someone tell me how to solve this problem , raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'django.contrib.admin.templatetags.admin_static': cannot import name 'RemovedInDjango30Warning' from 'django.utils.deprecation' (C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py) At first we try to save data's at sqlite3 it works , but few day's back we try to create discussion form and store the data's in sqlite3 it's shows an error continuously for each and every project , can someone give me a guidance to solve this ...... -
KeyError: 'DB_NAME' when doing makemigrations in django
I store all my secrets and database params in the dev.env file. I have 3 different settings files - base, dev and prod. There is an SQLite database in base, and I want to connect to Postgres in dev. So I upload my secrets with the environment variable like this: from dotenv import load_dotenv load_dotenv(os.environ.get('ENV_CONFIG', '')) And I override my database settings in dev settings file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': os.environ['DB_HOST'], 'PORT': os.environ['DB_PORT'], } } But when I run makemigrations with dev settings file: ./manage.py makemigrations --settings=app.settings.dev I get an error: File "/Users/admin/Desktop/Programming/Python/UkranianFunds/src/app/settings/dev.py", line 35, in <module> 'NAME': os.environ['DB_NAME'], File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DB_NAME' I checked and my secret with the key DB_NAME clearly appears in the settings file - I printed it successfully. The name of the database is correct. What are other reasons that cause that? -
The view products.views.get_product didn't return an HttpResponse object. It returned None instead
Here is my code, I am getting the same error again and again. def add_to_cart(request,uid): variant=request.GET.get('variant') product=Product.objects.get(uid=uid) user=request.user cart=Cart.objects.get_or_create(user=user, is_paid=False) cart_item=CartItems.objects.create(cart=cart,product=product) if variant: variant=request.GET.get('variant') size_variant=SizeVariant.objects.get(size_name=variant) cart_item.size_variant=size_variant cart_item.save() return HttpResponseRedirect(request.META.get('HTTP_REFFER')) ValueError at /product/tommy-hilfiger-blue-jeans The view products.views.get_product didn't return an HttpResponse object. It returned None instead. Request Method: GET Django Version: 4.0.4 Exception Type: ValueError Exception Value: The view products.views.get_product didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\MyPc\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 332, in check_response Python Executable: C:\Users\MyPc\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.7 -
How to go to another page after a function executes flask python
I have a function called getTableData() which runs another function get_table() and based on that get_table() output final function is called which renders a template and also routes to a different page. So the problem is its not routing to a different url (/tabdata) from get_final() function Flask code: @app.route('/api/getTableData', methods=['POST']) def getTableData(): value = request.json['value'] value=value[:8] url="https://some.com"+value df_time=get_table(url) return get_final(df_time) def get_table(url): driver = webdriver.Chrome(options=options) driver.get(url) abv = pd.read_html(driver.find_element(By.ID,"frm_hist").get_attribute('outerHTML'))[0] df_time = pd.DataFrame(abv) return df_time @app.route("/tabdata") def get_final(df_time): return render_template("new.html",df_time = df_time) Code Explanation: I am using the value from value variable then concat 2 strings to make the url and then passing the url to another function named get_table() which goes to that url and webscrapes the table and converts it into python dataframe. So using the returned python dataframe get_final() is called to render the template in a html file and also route to the /tabdata url. Everything is working well except the page is not routing to that url -
I want to create a directory like mysite.com/user
I'm using twitter API for authentication and I want to create directory like mysite.com/user after user get logged in. What should be actual view and path for this? models.py class TwitterUser(models.Model): screen_name = models.CharField(max_length=255) name = models.CharField(max_length=255) twitter_oauth_token = models.ForeignKey(TwitterAuthToken, on_delete=models.CASCADE) user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null = True) app/urls.py urlpatterns = [ path('', views.index, name='index'), path('twitter_login/', views.twitter_login, name='twitter_login'), path('twitter_callback/', views.twitter_callback, name='twitter_callback'), path('twitter_logout/', views.twitter_logout, name='twitter_logout'), ] Your input will be appreciated! -
how to use Unique Constraint for same models
I want to create only one object for the same users class MyModel(models.Model): user1 = models.ForeignKey(settings.AUTH_USER_MODEL,...) user2 = models.ForeignKey(settings.AUTH_USER_MODEL,...) class Meta: constraints = [ UniqueConstraint( fields=['user1', 'user2'], name='user_unique', ), # UniqueConstraint( # fields=['user2', 'user1'], # name='user_unique2', # ), ] I can solve the problem in another way, I just want to know how to do it with UniqueConstraint Adding another UniqueConstraint and moving the fields didn't solve the problem For example, for users X and Y, I only need one object -
I have tried creating a function for an employee where he can clock in and clock out for attendance
#Here are my Models# from django.db import models from django .contrib.auth.models import User GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female') ) class Employee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) eid = models.IntegerField(primary_key=True) salary = models.IntegerField() gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=1) contactno = models.CharField(max_length=10) email = models.CharField(max_length=30) country = models.CharField(max_length=30) city = models.CharField(max_length=20) pincode = models.IntegerField() address = models.CharField(max_length=60) def __str__(self): return self.user.first_name + ' ' + self.user.last_name class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1) attendance_date = models.DateField() in_time = models.TimeField() out_time = models.TimeField() description = models.TextField() def __str__(self): return str(self.employee) class Timesheet(models.Model): """ Timesheet model """ LOGGING_CHOICES = (('IN', 'IN'), ('OUT', 'OUT') ) # employee who recorded employee = models.ForeignKey(User, on_delete=models.CASCADE) recorded_datetime = models.DateTimeField(auto_now_add=True) clocking_time = models.DateTimeField() # whether the user has clocked in or out logging = models.CharField(max_length=3, choices=LOGGING_CHOICES) comments = models.TextField(blank=True, null=True) def __str__(self): return str(self.employee.first_name) class Meta: get_latest_by = 'clocking_time' # Here are my views# def clock_action(request): # Define function, accept a request and user details """Receives the users input e.g. clock in / out actions, stores and retrieves records to and from the database""" # When the employee clocks in/out the post is received, the date and time is recorded and it is logged to the employees … -
How group_by year list python?
im receiving this list from API [{u'criados': u'25/10/2022 00:50', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/9.pdf', u'id': 1, u'tipo': u'NAI', u'slug': u'Teste-1'}, {u'criados': u'25/10/2022 23:54', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/Profile.pdf', u'id': 2, u'tipo': u'NIP', u'slug': u'copa-06'}, {u'criados': u'27/10/2020 09:12', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/10.pdf', u'id': 3, u'tipo': u'NAI', u'slug': u'teste-2020'}] im trying to group this elements by year only year, so i try to use regoup template tag but doesn't work and i think i can use group_by by itertools or use pandas... or change what API returns, im confuse what is the best solution. please help me -
What are some potential reasons as to why an error would get thrown in Python but point to the wrong line?
So I am using Django and Python 3.9. I get a KeyError at /myapp/myroute, to which it tells me the value of the key I tried. The problem is it points to line 929, which is else:. if "qrp" not in request.session: request.session["qrp"] = "" # see if the ticket's qr code exists try: print("try1") request.session["qrp"] = f"""{request.session["iam"]}/UserQRCodes/{str(request.session["usid"])}.png""" obj = s3r.Object('iet-ticket-bucket', qrfn) obj.load() except botocore.exceptions.ClientError as e: print("except1") if e.response["Error"]["Code"] == "404": print("if16") # if not os.path.exists(us.QRPath): img = q.make(json.dumps({"id": request.session["usid"], "storename": s.StoreName})) iba = io.BytesIO() img.save(iba, format="PNG") # this can be rewritten to img.save(my_var, Format="PNG") to save it to a variable, which then can be pushed to an s3 bucket without writing to a file. # 1#img.save(floc + "/apache_django_files/qrcodes/users/" + str(request.session["usid"]) + ".png") s3 = boto3.client('s3') # 1#s3.upload_file(f"{floc}/apache_django_files/qrcodes/users/{request.session['usid']}.png", "iet-ticket-bucket", key) s3.put_object(Bucket="iet-ticket-bucket", Key=request.session["qrp"], Body=iba.getvalue(), ContentType="image/png") # 1#config = s3._client_config # 1#config.signature_version = botocore.UNSIGNED # 1#qrp = boto3.client('s3', config=config).generate_presigned_url('get_object', ExpiresIn=0, Params={'Bucket': "iet-ticket-bucket", 'Key': key}) request.session["qrp"] = qrp # 1#os.remove(floc + "/apache_django_files/qrcodes/users/" + str(request.session["usid"]) + ".png") change = True qrp = request.session["qrp"] I've done some googling, and granted I may be looking for the wrong thing, but does anyone have any possible suggestions as to what the problem is? If you could … -
Can't access all data from prefetch_related, only the first array item?
I have the following three models that are in a many-to-many relationship: PokemonTypesTest and BasePokemonTest are linked via an intermediary table WeakResistImmune class PokemonTypesTest(models.Model): name = models.CharField(max_length=25, unique=True) def __str__(self): return self.name class BasePokemonTest(models.Model): name = models.CharField(max_length=50, unique=True) base_hp = models.IntegerField() base_atk = models.IntegerField() base_def = models.IntegerField() base_spatk = models.IntegerField() base_spdef = models.IntegerField() base_speed = models.IntegerField() type1 = models.ForeignKey(PokemonTypesTest, null=True, on_delete=models.SET_NULL, related_name='pokemontype1') type2 = models.ForeignKey(PokemonTypesTest, null=True, on_delete=models.SET_NULL, related_name='pokemontype2') type3 = models.ForeignKey(PokemonTypesTest, null=True, on_delete=models.SET_NULL, related_name='pokemontype3') ability1 = models.CharField(max_length=25, default='n/a') #these abilities (ability1, ability2 and hidden_ability will need to be moved to a many-to-many table) ability2 = models.CharField(max_length=25, default='n/a') #where a pokemon id from basepokemon table is linked to a ability id hidden_ability = models.CharField(max_length=40, default='n/a') pokemon_id = models.IntegerField(default=0) weaknessResistanceImmune = models.ManyToManyField(PokemonTypesTest, through='WeakResistImmune') class WeakResistImmune(models.Model): #in the typing field, 1 is weakness pokemon = models.ForeignKey(BasePokemonTest, on_delete=models.CASCADE) weak_resist_immune = models.CharField(max_length=25) typing = models.ForeignKey(PokemonTypesTest, on_delete=models.CASCADE) multiplier = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return str(self.pokemon.name) I was going through the docs and thought the following would work: data = BasePokemonTest.objects.prefetch_related('weaknessResistanceImmune') Data returns the following query set <QuerySet [<BasePokemonTest: Base for - Bulbasaur>, <BasePokemonTest: Base for - Ivysaur>, <BasePokemonTest: Base for - Venusaur>, <BasePokemonTest: Base for - Mega Venusaur>, <BasePokemonTest: Base for - Charmander>]> I used the … -
django app: separation of concerns and optimizing big objects generated with for loop/dictionary comprehensions
When there is a need to generate a massive object in a Django project that will be used to populate a template, where it should be generated/stored? If - in example (posted below) - I populate a template with a dictionary object that is populated by a for loop statement (outside the function, in views.py), then that will force the server to generate this object in the process of starting its job. In other words, when I generate an object in views.py outside a function it takes a long time to run the server (the object is big). monthly_challenges = {} keys = range(1000000) values = range(1, 2000000, 2) for i in keys: for x in values: monthly_challenges[i] = x def index(request): months = list(monthly_challenges.keys()) return render(request, "challenges/index.html", { "months": months }) Is the approach mentioned the best way?? Having in mind the idea of separation of concerns I would like to know how and where is the wisest to generate an object with a big size content. How can I optimize the performance in this case? -
How to differentiate Basic/Premium plan users for premium-only features in Django REST?
I am working on a beta-stage writing tool SaaS that is built with NextJS, React, and Django REST. As I’m gaining some user base, I am starting to research on introducing a premium plan to the mix using Stripe. As most other SaaSs, I will have a subscription-based premium plan which grants access to premium-only features. However, even after days of research, I am still lost how this is commonly implemented in Django/Backend. Here is what I’ve thought of so far, but again, I am not sure if it’s the best/common way to accomplish this. User model has a ‘premium’ field which is either True or False Whenever user clicks on a premium-only API call, Django will check if user is premium or not to decide whether to make the actual API call. I currently have a '/user/me/' route which returns basic user information as API GET call. Upon successful stripe payment, stripe redirects user to the success_url. Then, somehow I will detect when user lands on success_url and then set that user’s premium field to True. I know this is not the ideal way, because I already see lots of issues/hurdles: How will I set ‘premium’ field back to … -
Django nginx prdoction doesn't show images media with domain
I deployed my small django app to nginx / gunicorn. With the server ip as domain it worked fine, but I pointed my domain name to my server and I can load the page but media files (images) are not showing up anymore. nginx config server { listen 80; server_name WWW.DOMAINNAME.COM; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/mysite; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } settings.py ALLOWED_HOSTS = ['www.DOMAINNAME.com'] STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = '/var/www/mysite/static/' Note: If I change back the Domain name to the server ip in the nginx config file and my django settings file, the media file load correclty. -
django app: is it possible to use `for loop` outside function in views.py?
I'm aware that I can create an object - like a dictionary - in views.py which can be used in a particular function. For example (views.py): # here `monthly_challenges` is working monthly_challenges = { "january": "Eat no meat for the entire month!", "february": "Walk for at least 20 minutes every day!", "march": "Learn Django for at least 20 minutes every day!", "april": "Eat no meat for the entire month!", "may": "Walk for at least 20 minutes every day!", "june": "Learn Django for at least 20 minutes every day!", "july": "Eat no meat for the entire month!", "august": "Walk for at least 20 minutes every day!", "september": "Learn Django for at least 20 minutes every day!", "october": "Eat no meat for the entire month!", "november": "Walk for at least 20 minutes every day!", "december": None } def index(request): months = list(monthly_challenges.keys()) return render(request, "challenges/index.html", { "months": months }) But is it possible to populate a template with a dictionary object populated by a for loop statement? I tried with the code below without a success: # here `monthly_challenges` is not working monthly_challenges = {} keys = range(1000000) values = range(1, 2000000, 2) for i in keys: for x in values: monthly_challenges[i] … -
What is the reason for not saving data in the database?
My target is to store data from the html form. I tried different ways, bellow way is one of them. But data is not stored in the database😥. What is the problem? Is the way appropriate? views.py: @api_view(['POST']) def employeeListView(request): if request.method == 'POST': jsonData = JSONParser().parse(request) serializer = EmployeeSerializer(data=jsonData) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False) else: return JsonResponse(serializer.errors, safe=False) def InsertAndInfo(request): if request.method == 'POST': name = request.POST.get('name') data = { 'name':name } headers = {'Content-Type': 'application/json'} read = requests.post('http://127.0.0.1:8000/api/employees/',json=data,headers=headers) return render(request, 'InsertAndInfo.html') models.py: class Employee(models.Model): name = models.CharField(max_length=30) email = models.EmailField(max_length=30) phone = models.IntegerField() serializer.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = "__all__" urls.py: path('', views.InsertAndInfo, name="InsertAndInfo"), path('employees/', views.employeeListView, name="employeeListView") -
Django Vue3 project js not found
we are making a project using django and vue3. In this project, when I run the project with django while the project is running in vue3, django cannot see the App.js and chunk.js files. How can I solve this problem? vue.config.js const { defineConfig } = require('@vue/cli-service') const BundleTracker = require('webpack-bundle-tracker') module.exports = defineConfig({ transpileDependencies: true, configureWebpack: { plugins: [ new BundleTracker({ path: __dirname, filename: 'webpack-stats.json' }), ], }, }) django settings.py WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'STATS_FILE': str(BASE_DIR.joinpath('frontend', 'webpack-stats.json')), 'POLL_INTERVAL': 0.1, 'IGNORE': [r'.+\.hot-update.js', r'.+\.map'], } } -
NOT NULL constraint failed: activities_activity.host_id
I'm creating a Django application where a logged in user can create an activity. For the login, I extended the allauth User model, including my own custom fields, which are stored in another model, called UserProfile; I am trying to use this UserProfile model Foreign Key for creating the activities. (I get an error when I try to use the User model) I'm continuously getting the same error: NOT NULL constraint failed: activities_activity.host_id I've tried to delete migrations and re-migrate, deleted the DB also. Everything creates successfully via the /admin panel, however I'm struggling to do it through the view.py file. This is what I have in the views.py def create_activity(request): if request.method == "POST": profile = UserProfile.objects.filter(user=request.user) print(profile) # Successfully prints the users profile form = ActivityForm(request.POST) form.host = profile # I'm pretty sure this is where I'm going wrong. if form.is_valid(): form.save() return redirect('activities') else: form = ActivityForm() context = { 'form': form, } return render(request, 'activities/new_listing.html', context) My UserProfile model looks like this: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') phone_number = models.CharField(max_length=30, null=False) postcode = models.CharField(max_length=500, null=True, blank=True) town_or_city = models.CharField(max_length=40, null=True, blank=True) street_address1 = models.CharField(max_length=80, null=True, blank=True) street_address2 = models.CharField(max_length=80, null=True, blank=True) county = models.CharField(max_length=80, … -
Django-allauth and logout issue with Google
I'm using django-allauth specifically and only for Google authentication. I'm experiencing a few odd issues: Logout from a Chrome browser and the user is still remembered upon login. The user is never redirected to a Google login. Log out from a Safari browser and the user is NOT remembered upon login, therefore they are directed to the Google login at the next login attempt. The desired result would be to always force users to go through the full login process. They should be directed to Google for their email and password. This allows users to share a computer and switch accounts. I've experimented with multiple configuration settings, but with no luck. Here are the current configs: ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = True LOGIN_REDIRECT_URL = '/stores/store_list' ACCOUNT_LOGOUT_REDIRECT_URL = 'home' ACCOUNT_SESSION_REMEMBER = False SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = 60 SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'offline', 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, } } } Is this something that is expected and directly tied to the session? Do I need to delete the session upon each logout? I tested by manually removing the … -
Reserving datasets from top to bottom of a list (database-table) for users avoiding race conditions (Django 4.1)
I start developing a Django web app that ist going to be used by hundreds of user at the same time. The app consits of a simple database table that lists unique tasks top-down. The first user that request some tasks should get the tasks from the top of the list. The next user that asks for tasks should get the next tasks and so on. How do I prevent, that users get the same tasks from the table when they ask for datasets at the same time? Is there the possibility of a race condition? -
Django - AttributeError: 'User' object has no attribute 'fullclean'
I am working on a django project in the intelji IDE. I am writing unit tests in the test.py file for the User model class. When runing the test.py file with the command "python manage.py test" it throws 2 errors on the test_username_cannot_be_blank method and the test_valid_user method. The error is the same for both methods (AttributeError: 'User' object has no attribute 'fullclean'). The IDE is also giving me a Instance attribute user defined outside init warnig on line 9 of the test.py file ("self.user = User.objects.create_user()") is where the compiler warning occurs. What excalty is the casue of the AttributeError and the compiler warning? # test.py file from django.test import TestCase from django.core.exceptions import ValidationError from .models import User class UserModelTestCase(TestCase): def setUp(self): self.user = User.objects.create_user( '@johndoe', first_name='John', last_name='Doe', email='johndoe@example.org', password='Password123', bio='The quick brown fox jumps over the lazy dog.' ) def test_valid_user(self): self._assert_user_is_valid() def test_username_cannot_be_blank(self): self.user.username = '' self._assert_user_is_invalid() def _assert_user_is_valid(self): try: self.user.fullclean() except ValidationError: self.fail('user should be valid') def _assert_user_is_invalid(self): with self.assertRaises(ValidationError): self.user.fullclean() # models.py file from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField() Looked on stackoverflow but could'nt find any solution to the problem. -
Django ORM not behaving as expected
So I have an application and I am working on optimizing some queries and am using django debug toolbar to analyze the SQL. So I accidentally put the prefetch_related call BEFORE the .objects in the chain for the query and it reduced my page load from about 500 queries to 13 as expected from prefetch_related except for the location in the chain it is, as seen below: latest_status = StationMaintenanceStatus.prefetch_related('station').objects.filter(station=station).latest('date') However, this is actually running in a production environment and works in development properly as well. But if I put the prefetch related anywhere later in the chain, my performance is back to 500 queries for the same page with zero effect on performance. Can anyone please explain to me why this is working? If I load the code in a shell session w/ manage.py and call the same code as above and supply it a Station object, it fails and throws and error like I would expect it to since the code is incorrect according to documentation. I am at a loss, and it feels bad having this in production however the performance gain is immense. Running Django 4.1.2 and Python 3.10 -
creating a django model object that accepts more than one input
I'm creating a bookstore website using django. I want to allow user to post their own books 'like goodreads' I want to allow the user upon creating his book to be able to write the most important quotes in his book for marketing the book. So I want to add an input in the form that allows adding a quote or multiple quotes 'like adding more than a number for a contact in contacts list using plus and minus button'. so what I can do in html, java and django model to make this? models.py: class books(models.Model): user= models.ForeignKey('User', related_name="user" , default= None, blank=True) name = models.CharField(max_length=80) cover = models.ImageField(upload_to='files/covers') price = models.IntegerField() description = models.CharField(max_length=500) authorname= models.CharField(max_length=30) position = models.CharField(max_length=30) wordbyauthor = models.CharField(max_length=500) category=models.ForeignKey(categories, on_delete=models.CASCADE, related_name="category" ) in html page: <form method="post"> {% csrf_token %} <label>Book Name</label> <input type="text" name="bookname" label="Book name"> <label>Book Cover</label> <input type="file" accept='image/*' name="bookcover"> <label>Price</label> <input type="number"> <label>Description</label> <textarea name="description"></textarea> <label>Author</label> <input type="text" name="author"> <label>Author description</label> <input type="text" name="audesc"> <input type="submit"> </form> so I want to add an html input element, django model and script that allows me to do this.