Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to do an inner join statement in django?
A little confused on how to do join's in Django. For example I have the following 3 tables: battlefield_weakresistimmune; id | weakResistanceImmune | multiplier | pokemon_id | typing_id ----+----------------------+------------+------------+----------- battlefield_basepokemontest; id | name | base_hp | base_atk | base_def | base_spatk | base_spdef | base_speed | ability1 | ability2 | hidden_ability | pokemon_id | type1_id | type2_id | type3_id ----+---------------+---------+----------+----------+------------+------------+------------+------------+-----------+----------------+------------+----------+----------+---------- 1 | Bulbasaur | 45 | 49 | 49 | 65 | 65 | 45 | Overgrowth | n/a | Chlorophyll | 1 | 12 | 4 | 2 | Ivysaur | 60 | 62 | 63 | 80 | 80 | 60 | Overgrowth | n/a | Chlorophyll | 2 | 12 | 4 | battlefield_pokemontypestest; id | name ----+---------- 1 | Normal 2 | Fighting 3 | Flying 4 | Poison I want to get the name of the Pokemon from basepokemontest, the condition and multiplier from weakresistimmune and the type name from pokemontypestest. I can easily do that in SQL via: SELECT poke.name, con.weak_resist_immune, type.name, con.multiplier FROM battlefield_basepokemontest poke INNER JOIN battlefield_weakresistimmune con ON poke.id = con.pokemon_id INNER JOIN battlefield_pokemontypestest type ON type.id = con.typing_id; name | weak_resist_immune | name | multiplier -----------+--------------------+--------+------------ Bulbasaur | Weak | … -
I have a query that checks if BVN or Phone _number exist in my db but I am trying to add a third item which is the channel used by user
I am working on an API that that takes BVN or Phone number and Channel from user. When they call the API I am to return a message based on the channel(If they used used, I will return text and if they used mobile banking, I will return html). What I have built so far will check pick any of BVN or PHone number supplied and check the channel.If user has been saved before I return "user exist" if not I will save. I have achieved this so far but I want to take if further to check for channel too. if the user with phone number "X" hits the API twice with different channel I want it to pass. I want to deny access only if the (phone number or bvn) and channel correspond with wants in the db. Serializer.py ` class SaveTermsSerializer(serializers.ModelSerializer): channel=serializers.CharField(required=True) bvn= serializers.CharField(max_length=15,allow_blank=True, required=False) phone_number=PhoneNumberField(allow_blank=True, required=False) # terms_status=serializers.CharField(max_length=25) class Meta: model = Consent fields = ['channel','phone_number', 'bvn', 'consent_status'] def validate(self, data): bvn = data.get('bvn') channel = data.get('channel') phone_number = data.get('phone_number') if channel.lower() not in ['ussd','mobile_banking','online_banking']: raise serializers.ValidationError("Invalid channel detected") if not (bvn or phone_number): raise serializers.ValidationError("BVN and Phone Number cannot be empty") if bvn and not … -
Field 'activity_id' expected a number but got <QueryDict: Django
I'm creating a small django CRUD project and working on creating the create functionality, however everytime I try to create an activity through teh sites frontend I get the following error Field 'activity_id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['DnM8yrfIrvYgvN6rShEOtR9DFwjpryNtHHs6ytHK1CSAYg3G9sm7YjkcHlpejJDt'], 'host': ['1'], 'name': ['testing testing'], 'date': ['2022-06-28'], 'start_time': ['19:20:58'], 'end_time': ['19:52:50'], 'location': ['test Location'], 'description': ['ewerwerwerwe']}>. When I create somethign through the /admin panel, it works as expected. here is my forms.py file: from django import forms from .models import Activity class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = ('host', 'name', 'date', 'start_time', 'end_time', 'location', 'description') def __init__(self, *args, **kwargs): """ Add placeholders and classes, remove auto-generated labels and set autofocus on first field """ super().__init__(*args, **kwargs) placeholders = { 'name': 'Activity Type', 'date': 'Date of Activity', 'start_time': 'Start Time', 'end_time': 'End Time', 'location': 'Location', 'description': 'Description', 'host': 'Host', } for field in self.fields: if self.fields[field].required: placeholder = f'{placeholders[field]} *' else: placeholder = placeholders[field] self.fields[field].widget.attrs['placeholder'] = placeholder self.fields[field].label = False this is the models.py file class Activity(models.Model): class Meta: verbose_name_plural = 'Activities' activity_id = models.AutoField(primary_key=True) host = models.ForeignKey(UserProfile, on_delete=models.CASCADE) name = models.CharField(max_length=254, null=False, blank=False) date = models.DateField() start_time =models.TimeField() end_time = models.TimeField() location = models.CharField(max_length=40, null=False, blank=False) description … -
Define a @property and @classproperty with the same name (Python, Django)
Background The Django LiveServerTestCase class has a live_server_url method with a @classproperty decorator. (django.utils.functional.classproperty.) The class starts its test server before any tests run, and thus knows the test server's URL before any tests run. I have a similar MyTestCase class that has a live_server_url @property. It starts a new test server before each test, and thus its live_server_url property can't be a @classproperty because it doesn't know its port until it is instantiated. To make the API for both consistent, so that all the test utility functions etc. in the code base can be used with both classes, the tests could be written to never reference live_server_url in setUpClass(), before all the tests run. But this would slow down many tests. Instead, I want MyTestCase.live_server_url to raise a helpful error if it is referenced from the class object rather than an instance object. Since MyTestCase.live_server_url is a @property, MyTestCase().live_server_url returns a string, but MyTestCase.live_server_url returns a property object. This causes cryptic errors like "TypeError: unsupported operand type(s) for +: 'property' and 'str'". Actual question If I could define a @classproperty and @property on the same class, then I would define a MyTestCase.live_server_url @classproperty that raises an error with a … -
Currency store in shorted form Python
enter code here write a program If we have gorcery store .. one customer come in shop and purchase some item and give 180$ our program automatically all cuurency notes store in shorted form an other customer come and purchse one item nad give 20$ alrady we have array in shorted form this 20$ automaticalyy store in shorted form """ import random import matplotlib.pyplot as plt import matplotlib.animation as anim # install matplotlib using (pip install matplotlib) # if you are using linux run this # sudo apt-get install --reinstall libxcb-xinerama0 def swap(A, i, j): a = A[j] A[j] = A[i] A[i] = a # this is buble sort algo def sort_buble(arr): if (len(arr) == 1): return for i in range(len(arr) - 1): for j in range(len(arr) - 1 - i): if (arr[j] > arr[j + 1]): swap(arr, j, j + 1) yield arr def insertion_sort(arr): if(len(arr)==1): return for i in range(1,len(arr)): j = i while(j>0 and arr[j-1]>arr[j]): swap(arr,j,j-1) j-=1 yield arr def quick_Sort(arr,p,q): if(p>=q): return piv = arr[q] pivindx = p for i in range(p,q): if(arr[i]<piv): swap(arr,i,pivindx) pivindx+=1 yield arr swap(arr,q,pivindx) yield arr yield from quick_Sort(arr,p,pivindx-1) yield from quick_Sort(arr,pivindx+1,q) def selection_sort(arr): for i in range(len(arr)-1): min = i for … -
How to make a date picker that does not select previous dates in Django
I want to make a date picker that does not select previous dates using Django. class DateInput(forms.DateInput): input_type = 'date' class TimeInput(forms.TimeInput): input_type = 'time' """class used for booking a time slot.""" class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['check_in_date', 'check_in_time', 'check_out_time', 'person', 'no_of_rooms'] widgets = { 'check_in_date': DateInput(), 'check_in_time': TimeInput(), 'check_out_time': TimeInput(), } """Function to ensure that booking is done for future and check out is after check in""" def clean(self): cleaned_data = super().clean() normal_book_date = cleaned_data.get("check_in_date") normal_check_in = cleaned_data.get("check_in_time") normal_check_out_time = cleaned_data.get("check_out_time") str_check_in = str(normal_check_in) format = '%H:%M:%S' try: datetime.datetime.strptime(str_check_in, format).time() except Exception: raise ValidationError( _('Wrong time entered.'), code='Wrong time entered.', ) # now is the date and time on which the user is booking. now = timezone.now() if (normal_book_date < now.date() or (normal_book_date == now.date() and normal_check_in < now.time())): raise ValidationError( "You can only book for future.", code='only book for future' ) if normal_check_out_time <= normal_check_in: raise ValidationError( "Check out should be after check in.", code='check out after check in' ) The above code is written in forms.py file. As you can see, I made a date picker but the problem is that the user can select any date but I want him to select …