Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove intermediate pages during Django all auth Facebook login?
I am using Django all-auth to enable Google & Facebook social logins to my application. The config is as follows: Django Allauth Settings: ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True) # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_AUTHENTICATION_METHOD = "email" # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_VERIFICATION = "none" # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_ADAPTER = "streampala.users.adapters.AccountAdapter" # https://django-allauth.readthedocs.io/en/latest/configuration.html SOCIALACCOUNT_ADAPTER = "streampala.users.adapters.SocialAccountAdapter" # https://django-allauth.readthedocs.io/en/latest/forms.html ACCOUNT_FORMS = { 'login': 'allauth.account.forms.LoginForm', 'signup': 'users.forms.AdvertisersSignUpForm', 'add_email': 'allauth.account.forms.AddEmailForm', 'change_password': 'allauth.account.forms.ChangePasswordForm', 'set_password': 'allauth.account.forms.SetPasswordForm', 'reset_password': 'allauth.account.forms.ResetPasswordForm', 'reset_password_from_key': 'allauth.account.forms.ResetPasswordKeyForm', 'disconnect': 'allauth.socialaccount.forms.DisconnectForm', } SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE": [ "profile", "email", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/youtube.upload", "https://www.googleapis.com/auth/youtube.force-ssl", ], "AUTH_PARAMS": { "access_type": "offline", }, }, "facebook": { 'METHOD': 'oauth2', 'SCOPE': ['email', 'public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'first_name', 'last_name', 'middle_name', 'name', 'name_format', 'picture', 'short_name' ], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v7.0', }, } This is what I see after clicking on Google/Facebook login button: And this comes up after completing Facebook login: I don't want any of these two intermediate screens, and tried modifying configuration as well. But these screens are not mentioned in the Django All-Auth docs so what am I missing? -
cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.9/site-packages/django/conf/urls/__init__.py)
ImportError at / cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.9/site-packages/django/conf/urls/init.py) Request Method: GET Request URL: https://aas-system.herokuapp.com/ Django Version: 4.0.1 Exception Type: ImportError Exception Value: cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.9/site-packages/django/conf/urls/init.py) Exception Location: /app/.heroku/python/lib/python3.9/site-packages/webpush/urls.py, line 1, in Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Tue, 01 Feb 2022 07:52:34 +0000 -
OperationalError no such column: ""
I am trying to create a "checklist" type form in Django based on a customer model. The checklist would just need to display the Name, RefNo, Contact Person and Email Address fields for each customer that has been saved into the database. However, I have then added a boolean field (isdone_IT14) which the user should tick to say whether that task for that customer has been done. When I try to load the checklists page the error: no such column: main_companyclass.isdone_IT14 is shown Please see the below code and full error message: Models.py: class CompanyClass(models.Model): #Company Only Fields CompanyName = models.CharField(max_length=50 , blank=False) RefNo = models.CharField(max_length=50 , blank=False ) #Contact Details ContactPerson = models.CharField( max_length=50, blank=False) EmailAddress = models.CharField(max_length=50, blank=False) #Services IT14 = models.BooleanField(default=True) # CheckList isdone_IT14 = models.BooleanField(default=False) def __str__(self): return ( self.CompanyName) Forms.py: class CompanyForm(ModelForm): class Meta: model = CompanyClass fields = '__all__' Views.py: class companyIT14(View): def get(self,request): it14s = CompanyClass.objects.filter(IT14 = True).order_by('CompanyName') form = CompanyForm() content = {'it14s':it14s , 'form':form} return render(request, 'main/Checklists/companyIT14.html', content) def post(self,request): it14s = CompanyClass.objects.filter(IT14=True).order_by('CompanyName') form = CompanyForm(request.POST) content = {'it14s': it14s, 'form': form} if form.is_valid(): form.save() return redirect('companyIT14') else: return render(request, 'main/Checklists/companyIT14.html', content) Template (companyIT14.html): {% extends "main/base.html"%} <html lang="en"> <head> <meta … -
Rename and move files in local system using website
I am developing a website with frontend react and backend as django where users can generate names of files in a particular format. Now this files will be in their local system or their local servers we can say. I need to rename the file and move that to a source folder. Is that possible using a website? I have heard this is possible but now sure how. Anybody knows how this can be done? -
How to fix 'Meta.fields' must not contain non-model field names: username for django graphene authentication endpoint
In my Django application I have created customer user model which uses email as username. class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True,) user_id = models.UUIDField( default=uuid4, unique=True, ) I am using graphene for APIs. For authentication endpoint I am following below steps, https://django-graphql-auth.readthedocs.io/en/latest/quickstart/ I am keep getting below error, sports_league-web-1 | File "/usr/local/lib/python3.10/site-packages/django_filters/filterset.py", line 71, in __new__ sports_league-web-1 | new_class.base_filters = new_class.get_filters() sports_league-web-1 | File "/usr/local/lib/python3.10/site-packages/django_filters/filterset.py", line 358, in get_filters sports_league-web-1 | raise TypeError( sports_league-web-1 … -
django: Password is not storing in DB with form
I'm trying to save some form inputs into the DB by extending the default auth library. For some reason, it is only saving the "email" in the DB. The password field was not stored and no error was shown. What am I doing wrong? Please help! Thanks! #views.py from django.shortcuts import render, redirect from django.http import HttpResponse from Accounts.forms import CreateUserForm # Create your views here. def registerPage(request): #debugDump form = CreateUserForm if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): return HttpResponse(request) form.save() context = { 'form':form } #return HttpResponse(form.error_messages) return render(request, 'accounts/register.html', context) #Accounts\forms from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.contrib.auth import get_user_model from django.http import HttpResponse User = get_user_model() class CreateUserForm(forms.ModelForm): password1 = forms.CharField() password2 = forms.CharField() class Meta: model = User fields = ['email','password1', 'password2'] def clean_email(self): ''' Verify email is available. ''' email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean(self): ''' Verify both passwords match. ''' cleaned_data = super().clean() password1 = cleaned_data.get("password1") password2 = cleaned_data.get("password2") if password1 is not None and password1 != password2: self.add_error("password2", "Your passwords must match") return cleaned_data -
Django Testing using Testcase error finding the batch_name
I am performing the testing for the models.py file Django After completing the test case for few classes I am stuck at a point First, let me share the models.py file class Batch(models.Model): commodity_id = models.PositiveIntegerField(null=True, blank=True) commodity_variety_id = models.PositiveIntegerField(null=True, blank=True) farm_id = models.ForeignKey(Farm, on_delete=models.CASCADE, related_name="batches", null=True, blank=True, db_column='farm_id') start_date = models.DateTimeField(null=True, blank=True) acerage = models.FloatField(verbose_name='Batch Acerage', help_text="In Acres;To change this value go to farms>crop" , validators=[MaxValueValidator(1000000), MinValueValidator(0.01)]) batch_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0)], help_text="In Percentage", default=100, null=True, blank=True) stage = models.CharField(max_length=100, choices=config.STAGE_CHOICES, default='germination', null=True, blank=True) expected_delivery_date = models.DateTimeField(null=True, blank=True) current_pdd = models.FloatField(null=True, blank=True) historic_pdd = models.FloatField(null=True, blank=True) current_gdd = models.FloatField(null=True, blank=True) historic_gdd = models.FloatField(null=True, blank=True) sub_farmer_id = models.PositiveIntegerField(null=True, blank=True) batch_status = models.CharField(max_length=100, choices=config.BATCH_STATUS, default='to_start') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) updated_by_id = models.PositiveIntegerField(null=True, blank=True) created_by_id = models.PositiveIntegerField(null=True, blank=True) historical_yield_per_acre = models.FloatField(verbose_name="Yield / Acre - Historical", null=True, blank=True) expected_produce = models.FloatField(default=0, null=True, blank=True) actual_produce = models.FloatField(default=0, null=True, blank=True) sop_adherence = models.FloatField(default=0, null=True, blank=True) actual_yield_per_acre = models.FloatField(default=0, null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) commodity_name = models.CharField(max_length=200, null=True, blank=True) batch_name = models.CharField(max_length=200, null=True, blank=True) batch_median_health = models.PositiveIntegerField(null=True, blank=True) pending_tasks = models.PositiveIntegerField(null=True, blank=True, default=0) history = HistoricalRecords() def __str__(self): return self.batch_name def save(self, *args, **kwargs): SOPMaster = apps.get_model('sop_management', 'SOPMaster') BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement') batch_sop_list = … -
Django Serializer - Combine fields from two models
I have two models namely: class B (models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255) class A (models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255) b = models.ForeignKey(B,on_delete=models.CASCADE,null=True) I want a serializer which returns a response like this: { "id": 1, "name": "test", "b_id": 2, "b_name": "test } -
Django can't find me .evn variables? decouple.UndefinedValueError: ENVIORNMENT not found. Declare it as envvar or define a default value
I am very new to Django and trying to configure python-decouple to use .env variables. I am getting DB_PASSWORD not found. Declare it as envvar or define a default value. when trying to run the server. The .env file is located in the root directory. Here is my code: raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: ENVIORNMENT not found. Declare it as envvar or define a default value. settings.py DATABASES = { "default": { "ENGINE": config("DB_ENGINE"), "NAME": config("DATABASE_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT", cast=int), "OPTIONS": { "init_command": "SET foreign_key_checks = 0;", }, } } .env SECRET_KEY='nvyj6_-&m@lg87$%l3@@#+r046ioem^18+ql*)t)' DEBUG=True DB_ENGINE=django.db.backends.mysql DATABASE_NAME=blogs DB_USER=root DB_PASSWORD= DB_HOST=127.0.0.1 DB_PORT=3306 Django==3.1.4 python-decouple==3.3 -
Confusion of using Django rest Frame work
So there is a thing I have been very confused about and even after search and watching youtube videos still my concept is not clear. I have created an app with frontend in react and used django rest framework for backend because I know the data that comes from react is in json which normal django doesnt understand. so that's it. Now there is one more app I am working on and my client told me to created an API. Now my questions why would I need an API if the app is only for web can't I use simple django for it? Or not creating an API and directly interacting with the app is bad idea? also can if I create an API do you think I can use it for mobile backend too. How would registration login and logout things work? -
Django Form with dependent ForeignKey forms on one Page
Good day, I am trying to implement django with a dependent foreignkey forms on one page. I have three moodels Store, Product, and ProductClothing. They are all ForeignKey related respectively. Users get to create their store seperately, and are redirected to the store detail view where they will now have to upload Products. But this time, I want them to upload both products and product clothing at once. Below is my models.py and views.py of what I have currently on the store detail view. Also the error I get is: error.py NOT NULL constraint failed: product_productclothing.product_id models.py class Store(models.Model): owner = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, unique=True) slug = AutoSlugField(populate_from='name', unique=True) description = models.CharField(max_length=255, blank=True) def __str__(self): return self.name class Product(models.Model): store = models.ForeignKey(Store, null=True, on_delete=models.SET_NULL) owner = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) title = models.CharField(max_length=255) price = models.DecimalField(max_digits=9, decimal_places=2, verbose_name=_("Regular price")) class ProductClothing(models.Model): CLOTHING_GENDER_CHOICES = ( ('M', 'Male',), ('F', 'Female',), ('U', 'Unisex',), ) CLOTHING_TYPE_CHOICES = ( ('dress', 'Dresses',), ('fabric', 'Fabrics',), ('shirt', 'Shirts',), ('suit', 'Suits',), ('tshirt', 'T-Shirts',), ('base_layers', 'Base_Layers',), ('blazer', 'Blazers',), ) product = models.OneToOneField(Product, on_delete=models.CASCADE) gender = models.CharField(max_length=10, choices=CLOTHING_GENDER_CHOICES, blank=True, null=True) clothing_type = models.CharField(max_length=255, choices=CLOTHING_TYPE_CHOICES, blank=True, null=True) def __str__(self): return self.product.title views.py @login_required def store_dashboard_view(request, slug): store = get_object_or_404(Store, slug=slug) … -
Model don't get objects in clean_<fieldname> functions
I have a question. İ have a custom user model and İ created a form for user creating. User model and Registration form code will be above. In clean methods for every fields User methods don't work. So I wanna get User model objects but User model returns empty QuerySet. But I have 2 users in my database. I try get user objects in clean_email and clean_username but both of get methods return empty QuerySet. Can anyone help me? User model: class UserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, date_of_birth, password=None): if not email: raise ValueError("Users must have email") if not username: raise ValueError("Users must have username") if not first_name: raise ValueError("Users must have first name") if not last_name: raise ValueError("Users must have last name") if not date_of_birth: raise ValueError("Users must have date of birth") email = self.normalize_email(email) first_name = normalize_name(first_name) last_name = normalize_name(last_name) user = self.model( email = email, username = username, first_name = first_name, last_name = last_name, date_of_birth = date_of_birth ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, date_of_birth, password=None): user = self.create_user( email = email, username = username, first_name = first_name, last_name = last_name, date_of_birth = date_of_birth, password = password ) user.is_admin = True … -
Group By Django queryset by a foreignkey related field
I have a model Allotment class Kit(models.Model): kit_types = (('FLC', 'FLC'), ('FSC', 'FSC'), ('Crate', 'Crate'), ('PP Box', 'PP Box')) kit_name = models.CharField(max_length=500, default=0) kit_type = models.CharField(max_length=50, default=0, choices=kit_types, blank=True, null=True) class AllotmentFlow(models.Model): flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) asked_quantity = models.IntegerField(default=0) alloted_quantity = models.IntegerField(default=0) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) dispatch_date = models.DateTimeField(default=datetime.now) send_from_warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) flows = models.ManyToManyField(AllotmentFlow) For a stacked graph I am trying to get the data of different kit_type alloted in different months. For that I have tried annotate but it isn't getting the desired results dataset = Allotment.objects.all().annotate( month=TruncMonth('dispatch_date')).values( 'month').annotate(dcount=Count('flows__kit__kit_type')).values('month', 'dcount') Expected Output: [{'month':xyz, 'kit_type':foo, count:123},...] I am getting the month and count of kit type from above but how do I segregate it by kit_type? -
Store all response of request module in database
So, I am using Django rest framework and to log all these API calls i am using Django rest framework API Logger module but does not log third party API calls. In my case i am using request module to deal with third party API calls and i want to store all the response into database of request module. please help me regarding this, Thanks. for example how i am using request module class LoginView(APIView): def get(self, request, *args, **kwargs): data = request.GET.copy() url = '{}/patient/mrn-login/'.format(settings.SNM_BASE_URL) params = {"no": data.get('no')} headers = {'Authorization': settings.SNM_AUTH_TOKEN} resp = requests.get(url, params=params, headers=headers) # Check the response status here if resp.status_code < 300: ''' When got the status 200 send the OTP to user telecom system here only ''' json_resp = resp.json().get('data') if data.get('channel') == 'email': otp_resp = send_email_otp(json_resp) else: otp_resp = send_otp(json_resp) return Response(otp_resp.json(), status=otp_resp.status_code) return Response({"message": "User doesn't exist"}, status=status.HTTP_404_NOT_FOUND) -
django form clean_<fieldname> method
I looked through similar answers but was surprised there was nothing in that list addressing such a basic question. My Django form is as follows: class JobApplicationForm(forms.Form): message = forms.CharField(widget=forms.Textarea) documents = forms.FileField(label="Documents", widget=DocumentUploadWidget) def clean(self): super().clean() def clean_documents(self): print ("clean_documents") return self.cleaned_data['clean_documents'] I can't find how to get clean_documents() to be called. The documentation says to use the form.is_valid() method but that doesn't work for me. Here is my sample Django shell session: Python 3.7.5 (default, Feb 23 2021, 13:22:40) [GCC 8.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from home.forms import JobApplicationForm >>> f = JobApplicationForm({'message':'sdfsfsdfs'}) >>> f.is_bound True >>> f.is_valid() False >>> f.errors {'documents': ['This field is required.']} >>> At no stage did I see the result of the print statement in the clean_documents() method. What else needs to happen to see it? -
Google Cloud storage upload method is returning signed URL. Django python
This is my upload image method from storages.backends.gcloud import GoogleCloudStorage storage = GoogleCloudStorage() def upload_image(file, dir_name, filename): try: target_path = '/static/images/' + dir_name + '/' + filename path = storage.save(target_path, file) return storage.url(path) except Exception as e: print(e) This is my settings in the django settings.py DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'bucket name' GS_PROJECT_ID = "project id" GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR,'google_cloud_credientials.json') ) I have used this tutorial for reference https://medium.com/@mohammedabuiriban/how-to-use-google-cloud-storage-with-django-application-ff698f5a740f This is returning me the signed URL for the file which I am using which is expiring after some time, but I want to have a public URL that will be available for any time. -
unoconv conversion from docx to pdf not working asynchronously
Goal I want to make a solution which can convert multiple docx files (submitted via separate parallel requests) to pdf. What I have tried and its behaviour After struggling with libreoffice --headless I came across unoconv which creates a listener for libreoffice in order to process multiple requests. Although, unlike libreoffice --headless, it does not fail to convert the docx files submitted via parallel requests, it seems that internally they are still processed sequentially. For example: If files A.docx & B.docx takes around 20 & 1.1 seconds respectively to get converted into .pdf individually, then, if both are submitted via 2 dedicated parallel requests and the conversion for both start at 00:00:00, the conversion process for both the files end at around 00:00:20. The behaviour I want However, the behaviour I want is to return the pdf for files as soon as they are converted eg: Just return the pdf for B.docx after 1.1 seconds, keep on converting A.docx and return that as well after 20 secs. Here's the minimal Django View for what I'm trying to do: def convert(request): docx_file = request.FILES['docx_file'] file = open(docx_file.name, "w+") file.write(docx_file.read()) cmd = "unoconv -f pdf %s" % file.name subprocess.Popen(cmd.split()).communicate(timeout=30) pdf_file_name = "%s.pdf" … -
How to Bulk Insert 5.5M records in mongodb through django model with in small time?
It took me around 6.5 to 7 hours in inserting bulk records from pandas dataframe of 5.5M records to my mongodb database through django model with 12-GB RAM. Below is the code for raised query. I want to make it faster to around 30 mins to 1 hour time, Is it possible ? # Split DF listDf = [] listDf = split_dataframe(completeDF02) ## This completeDF02 is the full dataframe having 5.5M records, So I split it with having 0.1M record in one batch in listDf list for item in listDf: df_records = item.to_dict('records') model_instances = [MyModel( Field1=record['Field1'], Field2=record['Field2'], Field3=record['Field3'], Field4=record['Field4'], Field5=record['Field5'], Field6=record['Field6'], Field7=record['Field7'], Field8=record['Field8'], Field9=record['Field9'], Field10=record['Field10'], Field11=record['Field11'], Field12=record['Field12'], Field13=record['Field13'], Field14=record['Field14'], Field15=record['Field15'], Field16=record['Field16'], Field17=record['Field17'], Field18=record['Field18'], Field19=record['Field19'], Field20=record['Field20'], Field21=record['Field21'], Field22=record['Field22'], Field23=record['Field23'], Field24=record['Field24'], Field25=record['Field25'] ) for record in df_records] MyModel.objects.bulk_create(model_instances) Is there an alternate way of doing bulk inserts to get more efficiency with speed ? If yes, then please let me know. -
How can I guard routes in Angular?
Currently, after logging in I'm able to get the JWT to the frontend. My app currently has a logging page as the landing page and as soon as the user logins the route checks for authentication to redirect to the guarded home path. My first intuition was to send a boolean from the backend (Django) and use that to create a guard. But I keep seeing that seems to be better practice to handle this in the front end. What I did was create an auth.service.ts and an auth.guard.ts. In the service, I try to retrieve the token from the browser and then verify that it hasn't expired. Then I call that method on the guard and return a boolean. Problem is that every time I look for the token in the local storage, I get back null. Is there any better way to get achieve this? auth.guard.ts import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree, } from '@angular/router'; import { Observable, of } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root', }) export class AuthGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) … -
New to Coding help in solving the issues im facing in django project
I am trying to create an event from Date A to Date B, i want to display that event in all following dates from date a to date b without me creating same event again and again. I am working on djnago -
MySQL Error 1146 and 1050 - Table does not exists and Table already exists
I've been migrating my database from the default Django sqlite3 to MySql but while running this command - py manage.py migrate --run-syncdb I get the following error django.db.utils.ProgrammingError: (1146, "Table 'blogue_test.blogueapp_category' doesn't exist") This is how I create the SQL Table manually CREATE TABLE blogueapp_category( -> id int NOT NULL AUTO_INCREMENT, -> name varchar(45) NOT NULL, -> PRIMARY KEY (id) -> ); Then re-run the same migrate command and it shows me the table already exists? MySQLdb._exceptions.OperationalError: (1050, "Table 'blogueapp_category' already exists") This is my Django models.py class Category(models.Model): name = models.CharField(max_length=255, db_index=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('category-list', kwargs={'cats': self.name}) I am merely a beginner in this and have been stuck with this same error for the past 2 days, even tried doing it in PostgreSQL but resulted in the same. Any help would be appreciated. -
how to get all data of price, qty from html in js and multiple it accordingly and add it into html in Django. anyone help me
I have attached the HTML on Photo Question - how to get all data of price, qty from HTML in js and multiple it accordingly and add it into HTML in Django. anyone help me. const x = document.getElementById("qty").innerHTML; const y = document.getElementById("price").innerHTML; const z = document.getElementById("total"); function calculator(qty, price) { let lowercase = price.toLowerCase(); const remove_price_string = lowercase.replace("only", ""); console.log(remove_price_string); let total = remove_price_string * qty; console.log(total); } calculator(x, y); -
Django image uploading error, "This field is required', "no files chosen"
I was working on a django project. I made a userprofiles app to manage(create, update) user's profile in my website, but it is not working properly. I am getting 'This field is required' & 'no file chosen' while making profile as a user and if I do blank=True in models profile_picture user pictures are not saving in the media url. I have tried so many tips from stackoverflow but they are not working. here is my code: # settings.py MEDIA_URL = '/media/' MEDIA_ROOT = str(BASE_DIR.joinpath('media')) # models.py from django.db import models from django.contrib.auth import get_user_model import uuid class UserProfile(models.Model): author = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='media/images/') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bio = models.TextField(blank=True) occupation = models.CharField(max_length=100) hobbies = models.TextField(blank=True) date_of_birth = models.TimeField() def __str__(self): return self.author.username + ("'s profile") # views.py from django.views.generic import CreateView from .forms import CustomUserCreationForm from django.urls import reverse_lazy class SignUpView(CreateView): form_class = CustomUserCreationForm template_name = "registration/signup.html" success_url = reverse_lazy("profile_create") # project-level urls.py from django.contrib import admin from django.conf import settings from django.urls import path, include from django.conf.urls.static import static from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path("accounts/", include("accounts.urls")), path("accounts/", include("django.contrib.auth.urls")), path("profile/", include("userprofiles.urls")), path("", TemplateView.as_view(template_name="home.html"), name="home"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # app-level urls.py … -
Need to get the value of Employee_name from User model to Employee model
# model 1 class User(models.Model): JOINING_ROLES_CHOICES= ( ('sde-intern','SDE Intern'), ('sde-trainee','SDE Trainee'), ('sde_1','SDE I'), ('ui/ux','UI/UX Designer'), ('quality-engineer-trainee','Quality Engineer Trainee'), ('quality-engineer','Quality Engineer'), ('product-manager','Product Manager'), ('technical-manager','Technical Manager'), ('technical-architect','Technical Architect'), ('technical-lead','Technical Lead') ) BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) employee_name = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=100,default=None) aadhar=models.CharField(max_length=100,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) joining_role=models.CharField(max_length=250,choices=JOINING_ROLES_CHOICES,null=True) relieving_role=models.CharField(max_length=250,null=True) joining_Date=models.DateTimeField(max_length=8,null=True) relieving_Date=models.DateTimeField(max_length=20,null=True) def __str__(self): return self.firstname #model 2 class Employeename(models.Model): employee = models.ForeignKey(User, related_name='employee', on_delete=models.CASCADE) employee = models.ManyToManyField(User) def __str__(self): return self.employee I need to get the employee_name value from the User model to the Employeename model. Is there any ways to get only employee_name to the employee. while i tried the above code it it throwing an error as mentioned below: TypeError at /admin/App/employee/3/change/ str returned non-string (type ManyRelatedManager) -
How else can i write this django custom validation othere than try and except
how else can i frame this django custom validation function to validate US phone number other than try and except block def validate(value): if re.match(r"[+]?[1\s-]*[\(-]?[0-9]{3}[-\)]?[\s-]?[0-9]{3}[\s-]?[0-9]{4}",value): return True else: return False