Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: run user provided python code : using exec or seval
I have a Django, I have to run user provided python code. I know it can be very harmful. After going through net i found this https://github.com/ellxc/seval the author mentions that seval has not been formally tested, and may have bugs. It has been implemented to attempt to ensure safe sandboxed execution, but there could be bugs. Use at your own risk. I am not sure how safe it is Can anyone guide in this regard how can i achieve this. currently i am doing allowed_param = { "priceDaily": priceDaily, "volumeDaily": volumeDaily, "priceWeekly": priceWeekly, "volumeWeekly": volumeWeekly, "priceMonthly": priceMonthly, "volumeMonthly": volumeMonthly, "parameters": parameters, "score": score } exec(customMethod,allowed_param) I need to do arthimetic operations -
Trouble converting SQL query to django
I am trying to convert this SQL query (which works flawlessly in mySQL) to Django ORM so that it can be used in a PostgreSQL environment (as the SQL query is invalid for PG). I have tried several different ways using aggregate and annotate but I just can't figure it out. What I am trying to do is count the number of entries of each type (there are 3 types in total), in each month, 6 months either side of the current date! The working SQL query is select count(c.id) as Quantity, date_format(expiry, '%Y-%m') as Expiry, type from certificate as c join type as t on t.id = c.type_id where expiry >= date_format(date_sub(now(), interval 6 month), '%Y-%m-%d') and expiry <= date_format(date_add(now(), interval 6 month), '%Y-%m-%d') group by month(expiry), type order by expiry asc I changed the 'date_format' into a postgres 'to_char' but then I can't seem to group by 'month(expiry)' and an ORM solution seems to be a much better way to go. The main Certificate model is as follows: class Certificate(models.Model): epc_rating = models.IntegerField(null=True, db_index=False) building_area = models.IntegerField(db_index=False) building_emissions = models.DecimalField(max_digits=6, decimal_places=2, db_index=False) energy_usage = models.DecimalField(max_digits=6, decimal_places=2, db_index=False) refrig_weight = models.IntegerField(db_index=False) ac_output = models.IntegerField(db_index=False) annual_heating = models.CharField(blank=True, null=True, max_length=50, … -
BeautifulSoup (bs4) not getting elements with find_all nor select nor select_one
Example Url to be crawled: www.yelp.com/biz/dallas-marketing-rockstar-dallas?adjust_creative=3cZu3ieq3omptvF-Yfj2ow&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=3cZu3ieq3omptvF-Yfj2ow' My code: def get_websites(): for yso in Company.objects.filter(crawled=False, source='YAG'): r = requests.get(yso.url) soup = BeautifulSoup(r.content, 'lxml') if soup.select_one(".g-recaptcha") != None: sys.exit("Captcha") soup_select = soup.select_one("a[href*='biz_redir']") try: yso.website = soup_select.text print('website for %s added' % (yso.website)) except Exception as e: print(e) print('no website for %s added' % yso.name) if not yso.crawled: yso.crawled = True yso.save() using lxml results in soup.select_one("a[href*='biz_redir']") being equal to None, soup.select("a[href*='biz_redir']") being an empty list, and soup.find_all("a[href*='biz_redir']") being an empty list. using html.parser results in soup.select_one("a[href*='biz_redir']") being equal to None, soup.select("a[href*='biz_redir']") being an empty list, and soup.find_all("a[href*='biz_redir']") being an empty list. lxml version 4.5.0 beautifulsoup version 4.9.3 I need help. Please help. Thanks Edit: Changing "a[href*='biz_redir']" to just a results in the same thing. There is something more fundamentally wrong than syntax, if syntax is even wrong. -
Plotly output shows empty Plot in Djang
I was creating a plot for a Django app and in the first run created the code in an isolated environment. Once i was moving into the django app I can only see an empty plot in the app. Where I am not sure is the code about the slider and traces. Could somebody have a look and see if there are any issues i need to clear out? encoded_image = base64.b64encode(open(path_to_file, 'rb').read()) img = 'data:image/;base64,{}'.format(encoded_image) layout = go.Layout() data = [] fig = go.Figure(data=data, layout=layout) traces = {} for step in [1,2,3]: fig.add_trace(go.Scatter( visible=False, x=x_pos[activations[::-1]]+step*-30, y=y_pos[activations[::-1]], )) fig.data[0].visible=True steps=[] for i in range(len(fig.data)): step = dict( method="update", args=[{"visible": [False] * len(fig.data)}, {"title": "Slider switched to step: " + str(i)}], # layout attribute ) step["args"][0]["visible"][i] = True # Toggle i'th trace to "visible" steps.append(step) sliders = [dict( active=1, currentvalue={"prefix": "Frequency: "}, pad={"t": 50}, steps=steps )] xlim = [0, width] ylim = [0, height] fig.update_layout( images= [dict( source='data:image/png;base64,{}'.format(encoded_image.decode()), xref="paper", yref="paper", x=0, y=1, sizex=1, sizey=1, xanchor="left", yanchor="top", #sizing="stretch", layer="below", )], xaxis_showgrid=False, yaxis_showgrid=False, xaxis_zeroline=False, yaxis_zeroline=False, xaxis_visible=True, yaxis_visible=True, width=width, height=height, sliders=sliders, #template="plotly_white" xaxis=dict(range=[xlim[0],xlim[1]]), yaxis=dict(range=[ylim[0],ylim[1]] ) ) data = list(traces.values()) fig = go.Figure(data=data, layout=layout) plot_1400 = plot(fig, include_plotlyjs=False, output_type='div') return plot_1400 -
Django Admin not redirecting after loging in... Response is 200
I'm developing an application using DRF and when I try to login to my admin dashboard it gives POST /admin/login/?next=/admin/ HTTP/1.1" 200 2350 but it doesn't redirect me to /admin. The strange thing is that everything worked yesterday. I'm also using React for the front-end and I have a sign-in page that uses obtain_auth_token from DRF. The Sign In page worked yesterday as well but today it doesn't. I created a super user, made sure that the user has super user privileges and it still doesn't redirect me to the login page. Here's my settings.py file """ import os from pathlib import Path import dj_database_url import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] AUTH_USER_MODEL = 'PaymentsApp.Account' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ] } # Application definition INSTALLED_APPS = [ 'corsheaders', 'PaymentsApp', 'rest_framework', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
Django. DEBUG in production
I'm writing my first real project in Django and I have a problem with properly setting DEBUG in development and production. In my settings.py project file I have: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DJANGO_DEBUG', 'True') == 'True' So I expect that it should work as follows. By default DEBUG is set to True (I use this in my development). But on my production server I have an environmental variable DJANGO_DEBUG set to "False" so Django should set DEBUG to False. But this does not work! When I go to my_website/notexistingurl I see Django detail error page which says that I have DEBUG set to True in my settings.py file. And to make this completely unclear to me, when I open a python shell on my server it says that os.environ.get('DJANGO_DEBUG', 'True') == 'True' is False. Does anyone have an idea what I am missing? Because to me it looks like two completely contradictory things! -
Django and prefetch_related Across Nested Relationships in a Custom Manager With to_attr Doesn't Attach Results to Model Instances
Consider a task list app with an editor that saves the state of the task list as a SnapShot after each edit (i.e., after inserting, editing, or deleting a TaskItem, a new SnapShot is generated, capturing the new state of the task_items, and their positions in the TaskList). Here is a simplified model: from django.db.models import Prefetch class TaskList(models.Model): objects = AnnotatedQuerySet.as_manager() class SnapShot(models.Model): task_list = models.ForeignKey(TaskList, on_delete=models.CASCADE) EDIT='ED' WORKEDIT='WE' LIVE = 'LI' STATUS_TYPES = ( (EDIT, 'Edit'), (WORKEDIT, 'Working Edit'), (LIVE, 'Live'), ) status = models.CharField(max_length=2, choices=STATUS_TYPES, default=EDIT) task_items = models.ManyToManyField(TaskItem, through='TaskItemInclude') class TaskItem(models.Model): content = models.TextField() class TaskItemInclude(models.Model): snapshot = models.ForeignKey(SnapShot, on_delete=models.CASCADE) task_item = models.ForeignKey(TaskItem, on_delete=models.CASCADE) position = models.SmallIntegerField() class Meta: ordering = ['position'] class AnnotatedQuerySet(QuerySet): def with_task_items(self, mode): if mode == SnapShot.LIVE: ti_qs = TaskItem.objects.filter(snapshot__status=SnapShot.LIVE) elif mode == SnapShot.WORKEDIT: ti_qs = TaskItem.objects.filter(snapshot__status=SnapShot.WORKEDIT) else: raise ValueError('mode must be LIVE or WORKEDIT.') return self.prefetch_related( Prefetch('snapshot_set__task_items', queryset=ti_qs, to_attr='fetched_task_items'), ) SnapShot, via its relationship with TaskItem through TaskItemInclude, captures the state of the TaskList. For each TaskList, there is one publicly visible live (SnapShot.LIVE) SnapShot, one current working edit (SnapShot.WORKEDIT), and possibly multiple inactive edits (SnapShot.EDIT). Inactive edits (SnapShot.EDIT) are saved for undo/redo/restore operations. My goal is to present the entire … -
Specify heigh of images in css doesn't work
I am currently working on a django blog. However, I am experiencing some difficulties with the size of the post thumbnails. Here's a picture: What I marked in yellow is how the image should be filling the space. The width is fine, but the heigh isn't working well as you can see. Here's the code: {% extends 'base.html' %} {% load static %} {% block content %} <style> img { height: 100%; width: 100%; } </style> <!-- Post--> {% for obj in object_list %} <div class="row d-flex align-items-stretch"> {% if not forloop.first and not forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the image {% endif %} <div class="text col-lg-7"> <div class="text-inner d-flex align-items-center"> <div class="content"> <header class="post-header"> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> <a href="{{ obj.get_absolute_url }}"> <h2 class="h4">{{ obj.title }}</h2> </a> </header> <p>{{ obj.overview|linebreaks|truncatechars:200 }}</p> <footer class="post-footer d-flex align-items-center"><a href="#" class="author d-flex align-items-center flex-wrap"> <div class="avatar"><img src="{{ obj.author.profile_picture.url }}" alt="..." class="img-fluid"></div> <div class="title"><span>{{ obj.author }}</span></div></a> <div class="date"><i class="icon-clock"></i> {{ obj.timestamp|timesince }} ago</div> <div class="comments"><i class="icon-comment"></i>{{ obj.comment_count }}</div> </footer> </div> </div> </div> {% if forloop.first or forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the … -
Getting a list from ListAPIView
I'm trying to get a list of an object "Contract" on a simple HTML page from a ListAPIView. But I cant get it to print what i need. It returns a Response. as needed: Response But it doesn't show anything on an HTML page (template in this case): {% extends "main.html" %} {% block contract %} <h1> Hello </h1> {% if contract_list %} <ul> {% for contract in contract_list %} <li> <h1> {{ contract.contractName }} </h1> </li> {% endfor %} {% else %} <h1>There are no contracts in the library.</h1> {% endif %} {% endblock %} It doesn't see contract_list at all. What am I doing wrong? Here it is in Views.py: class ContractSerializer(serializers.ModelSerializer): class Meta: model = Contract fields = ('contractName','zakupkiId','dateStart','dateEnd','display_tasks','get_absolute_url') class ContractView(generics.ListAPIView): model = Contract template_name = 'contracts/contract_list.html' # context_object_name = 'cotracts' # queryset = Contract.objects.all() def get(self, request): contracts = Contract.objects.all() # the many param informs the serializer that it will be serializing more than a single article. serializer = ContractSerializer(contracts, many=True) # render_classes = render(request, 'contract_list.html') return Response({"contracts": serializer.data}) And urls.py url(r'^contracts/$', views.ContractView.as_view(), name='contracts') -
How to add map on site?
I am new to djnago. I want to add a map to the site, where the user can select places on it, which will be saved to the database. I found how the user can select a location on the map: https://developers.google.com/maps/documentation/embed/get-started?hl=ru, but I do not know how to save it to the model -
Django ORM filter SUM different related objects
I have the following models: class Developer(models.Model): name = models.CharField(max_length=100) class Skill(models.Model): code = models.CharField(max_length=30) class Experience(models.Model): date_from = models.DateField(blank=True, null=True) date_to = models.DateField(blank=True, null=True) developer = models.ForeignKey(Developer, related_name='experience', on_delete=models.CASCADE) class SkillExperience(models.Model): skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name='skill_experience') experience = models.ForeignKey(Experience, on_delete=models.CASCADE, related_name='skill_experience') years_experience = models.IntegerField() I need a query to retrieve Developers that have at years_experience of at least 5 in skill code 'python', for example. However I can't simply do Developer.objects.filter(skill_experience__years_experience__gte=5) because I could have two experiences in Python but one 3 years and another one 2 years and that won't show in the query above. So I need to sum up all the years_experience that are from skill__code="Python" and evaluate it. Is there some way to do it with a single query? -
Content not showing on page using ListView
I'm trying to show data from database using ListView but the nothing would show on the page even though database has data views.py class CatAdoption(ListView): model = Cat template_name = 'adoptions/adoptionhome.html' context_object_name = 'cats' urls.py from .views import CatAdoption, DogAdoption, OtherAdoption urlpatterns = [ path('adoption-home/', CatAdoption.as_view(), name='adoptionhome'), adoptionhome.html <div class="animals"> {% for animals in cats %} <div class="animalpictures"> <div class="animalInfo"> <img alt="animalPic" src="https://1590597482.jpg" alt=""> <div class="animalDesc"> <h1>{{ animals.name }}</h1> <p>{{ animals.description }}</p> </div> </div> </div> {% endfor %} </div> (I have same code for another blog page which shows all contents from database) -
how customize User validator to accept whitespaces
I want have custom validation for User to create name user with whitespaces in name. I do this like below but, I create User2 and change regex expression but it not changed validation conditions, it's not work. Have anybody idea why or how instead of I can do it? models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User from django.contrib.auth.validators import UnicodeUsernameValidator class MyUnicodeUsernameValidator(UnicodeUsernameValidator): print('test My') regex = r'^[\d]' message = _( 'Enter a valid username. This value may contain only letters, ' 'numbers, and @/./+/-/_ characters.' ) flags = 0 class User2(User): username_validator = MyUnicodeUsernameValidator() print(username_validator) view from django.shortcuts import render, get_object_or_404 from .models import User2 from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import logout from blog.models import Article class MyUserCreationForm(UserCreationForm): class Meta: model = User2 fields = ("username",) def sign_up(request): context = {} form = MyUserCreationForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return render(request, 'accounts/index.html') context['form'] = form return render(request,'registration/sign_up.html', context) -
how to display a single vendor to its related product in django?
well, I am a beginner but a mid-level beginner and I am building an e-commerce website. I have vendor, customer and products which relate to a specific vendor. I have made a view to display the all kind of products on the page and I have also parsed the Vendor model in products view. but I am getting all vendors on a single product which shows that code is not working well as it should have. I hope you guys got the point what I want to ask? for convenience here is the code. views.py: def products(request): vendor = Vendor.objects.all() products_list = Item.objects.all() context = { 'vendors': vendor, 'products': products_list, } template = 'vstore/products.html' return render(request, template, context) products.html: <div class="row"> {% for item in products %} <div class="col-3"> <div class="item"> <div class="strip"> <figure> {% if item.discount >= 20 %} <span class="ribbon off">{{item.discount}}% OFF</span> <a href="{% url 'product_detail_view' item.pk %}" class="strip_info"> <img class="" src="{{ item.image.url }}" alt="Vendor's Photo"> </a> {% else %} <a href="{% url 'product_detail_view' item.pk %}" class="strip_info"> <img class="" src="{{ item.image.url }}" alt="Vendor's Photo"> </a> {% endif %} </figure> <ul> <li><span class="loc_open">{{ item.name }}</span></li> <li> <div class="score "><div class="score "><span class="">{% for vendor in vendors %}{{vendor.name}}{% endfor %}<h5><div … -
Better way to optimize bulk_create when uploading CSV file, with records related to junction model?
I have the following view: ### VIEW ### def project(request, project_id): creator_id = request.user.id # Get project project = get_object_or_404(Project, pk=project_id, creator_id=creator_id) # Get all backers all_backers = project.backers.all().distinct() # CSV UPLOAD csvform = csvUploadForm() if request.method == 'POST': csvform = csvUploadForm(request.POST, request.FILES) if csvform.is_valid(): csvform = csvform.save(commit=False) csvform.for_project_id = project_id csvform.creator_id = creator_id csvform.save() # READ CSV csv_file = csvform.csv data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) backers_list = csv.reader(io_string, delimiter=',', quotechar='"') objs = [ Backer( backer_number=row[0], backer_uid=row[1], name=row[2], email=row[3], shipping_country=row[4], shipping_amount=row[5], reward_title=row[6], backing_minimum=row[7], reward_id=row[8], pledge_amount=row[9], rewards_sent=row[10], pledged_status=row[11], notes=row[12], pid=project_id ) for row in backers_list ] try: msg = Backer.objects.bulk_create(objs) returnmsg = {"status_code": 200} print('imported successfully') except Exception as e: print('Error While Importing Data: ',e) returnmsg = {"status_code": 500} # Add backer_id and project_id in Backed new_backers = Backer.objects.filter(pid=project_id) backed_ids = [ Backed( backer_id=bid.id, project_id=project_id ) for bid in new_backers ] try: msg = Backed.objects.bulk_create(backed_ids) returnmsg = {"status_code": 200} print('imported successfully') except Exception as e: print('Error While Importing Data: ',e) returnmsg = {"status_code": 500} return redirect('project', project_id=project_id) else: csvform = csvUploadForm() ... Through this view I am uploading a CSV file, creating a list of it and using bulk_create to push it to model (Backer), in order to speed … -
Django problem with request.get to postgresql
Getting stuck with this issue, I've got a table that has date, category and sum and I'm trying to make a query that can choose between dates to get records, but when i pick dates it screams "column "2020-12-12" does not exist" views.py def outgoings_history(request): if request.method == "POST": date_from= request.POST.get('date_from') date_to= request.POST.get('date_to') search_result = Outgoings.objects.filter(user=request.user).order_by('-date')\ .raw('SELECT suma, kategoria, date FROM outgoings WHERE date BETWEEN "2020-12-12" AND "2020-12-12"') return render(request, 'outgoings_history.html', {'data': search_result}) else: displaydata = Outgoings.objects.filter(user=request.user).order_by('-date') return render(request, 'outgoings_history.html', {'data': displaydata}) forms.py class PickADate(forms.Form): date_from= forms.DateField(widget=DateInput()) date_to= forms.DateField(widget=DateInput())[enter image description here][1] The date '2020-12-12' is just a example and it has records this day but still doesn't show anything -
react send image file to api with axios
I have the following axios call in my app: export const createProduct = (form) => { const requestString = inventoryApiString + "products/"; return axios .post(requestString, form, getAuthHeader()) .then((Response) => { return { product: Response.data, message: null, }; }) .catch((Error) => { let errorMessage = getErrorMessage(Error); return errorMessage; }); }; And this is the content of key photo of parameter form: I am putting the content of the file field in the form when the user selects a file, but I get this error from Django Rest Framework backend api: {"photo":["La información enviada no era un archivo. Compruebe el tipo de codificación del formulario."]}, which means Information sent is not a file. Check the codification type of the form. I don't know what it means. -
How to set the name value and choice field value in html form fields without using django-forms?
Suppose I want to give user 2 option in html option form to choose 1. How can user user select one from html form without using django form?need views.py,models.py,index.html coding help Sample html code: <form method="POST"> <div class="form-row"> <div class="name">Name</div> <div class="value"> <div class="input-group"> <input class="input--style-5" type="text" name="name" required> </div> </div> </div> <div class="form-row"> <div class="name">Applying In</div> <div class="value"> <div class="input-group"> <div class="rs-select2 js-select-simple select--no-search"> <select name="subject" required> <option disabled="disabled" selected="selected"> Applying Department</option> <option>Backend</option> <option>Mobile</option> </select> <div class="select-dropdown"></div> </div> </div> </div> </div> -
is there a method to create a text field and color words in text in django?
i created a django project : so in my page html , i have a list of words colorated with different background colors : hello (colored in red) world (colored in yellow) i do this with : <span class="token-label" style="background-color=red">hello</span> in the same page , i want to display the text which contains the two words , but i want to colors the words in the text according to colors of each word: hello, i'am here ! hello world ! with "hello" colored with red and "world" in yellow -
How to use a view function on all pages in Django?
I'm building an app in Django in which I have a layout where I have the navbar and I extend this layout to each page. In order to have the navbar to receive the proper variables from the view I have to write the same code on each view. There has to be a way to write this code once and affect directly the layout so I won't need to type it multiple times but I haven't found the answer. How can I write the function one time? Something like a global variable in Django I guess. I hope I managed to explain myself ok, thanks in advance! -
Media files not displaying when DEBUG = False; what are the prerequisites to get them to show?
As I state in the title, when I set DEBUG = False in my project's settings file, the files from my media directory (the one the user uploads) don't display. The files from my static directory (the CSS and JavaScript files) load properly. I looked at this answer, but I don't understand the prerequisites to get this to work. I am testing this on my local machine, where I only have Django and PostgreSQL installed. I don't have any Apache servers running, as far as I'm aware. I want to deploy my app on Amazon AWS, so I'd like to try out how it will look in production there before I deploy it to Amazon AWS. Here are the relevant parts of my settings.py file: DEBUG = False ALLOWED_HOSTS = ['*'] STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', ] -
Django form.is_valid() always return false
I'm trying to make a login system in Django but I just can't go through Django form.is_valid statement because It returns false everytime.If I just type my usernameand passwordand submit the form, I can get the request.POSTdata but form.is_valid()still returns false. My Django view is at below @csrf_exempt def login_system(request): if request.method == 'POST': form = AuthenticationForm(request.POST) print(request.POST) if form.is_valid(): form.save() print("form is valid") username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username= username, password= password) login(request, user) return redirect("/") else: form = AuthenticationForm() context = {'form': form} return render(request, 'registration/login.html', context) and this is the htmlfile I've been trying to create a valid form. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method='post' action="{%url 'login' %}"> {%if form.errors %} <p>Error occured try again</p> {%endif%} {{form}} <input type="submit" value="login"> </form> </body> </html> -
Can't add new user or group in django admin
I am trying to add new user and group in my newly created django web from admin panel . But it shows following error when I click save. This the admin panel of my django website Here new group "group1" is creating ''' OperationalError at /admin/auth/group/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/auth/group/add/ Django Version: 2.1.5 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: G:\MyPythonProject\django_web\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 298 Python Executable: G:\MyPythonProject\django_web\venv\Scripts\python.exe Python Version: 3.9.0 Python Path: ['G:\MyPythonProject\django_web\web_project', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39', 'G:\MyPythonProject\django_web\venv', 'G:\MyPythonProject\django_web\venv\lib\site-packages'] Server time: Sat, 12 Dec 2020 18:18:33 +0000'''' -
How can i add google maps in django which takes a location from user and his desired location and then calculates the distance between the locations?
I created a an app which adds map in page using 'https://www.fullstackpython.com/blog/maps-django-web-applications-projects-mapbox.html' this refernce. Now i want to take userlocation and then user can enter his desired location and then calculates the distance between them. -
POST returns "detail": "Method \"GET\" not allowed."
The way the project works is there should be a random code that is given in creating a room (avoiding duplicates and the guessing a code that isn't taken) and the host should create their own name. In the files, I've created the room and generated a random code that should be given when creating a room, but I receive an HTTP 405 Method Not Allowed. I'm attempting to POST and not GET so I'm confused as to why that's happening; and the other parameters (code and host) do not show up. I assumed the code and host key would show up in the create method, but it doesn't. I would also like to add that I receive and Integrity Error regardless of changing the serializer to add id, code, and host to the serializer or if I leave the code the way it is in the screenshots. models.py from django.db import models import random import string # Create your models here. def code(): """ function randomly creates room access code """ length = 7 while True: code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length)) if Room.objects.filter(code=code).count() == 0: break return code class Room(models.Model): """ sets up room requirements and stores it …