Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I get empty form? How to automatically create Iniline models?
There are 2 forms on one page. There are 2 models: 1. Product. 2. SpecialPrice. SpecialPrice is linked via FK to Product. At the same time, SpecialPrice is Inline model in Product. The fields of the SpecialPrice form are automatically created using JS. That is, them may be the n-th number. It is necessary to create a record for each created field. In principle, I guess how to do it - use the cycle to drive the values obtained. But the problem is that for some reason None comes from the form. Please help me. class ProductsCreate(CreateView): model = Product form_class = ProductCreateForm http_method_names = ['get', 'post'] def get_initial(self): initial = super(ProductsCreate, self).get_initial() initial['request'] = self.request return initial def get_context_data(self, *args, **kwargs): ctx=super(ProductsCreate, self).get_context_data(*args, **kwargs) ctx['special_form'] = SpeciallyPriceForm() return ctx def get(self, request, *args, **kwargs): self.object = None if kwargs.get('slug'): category = Category.objects.filter(slug=kwargs.get('slug')).first() self.initial.update({'category': category}) return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): self.object = None form = ProductCreateForm(request.POST, request.FILES, initial={'request': request}) special_form = SpeciallyPriceForm(request.POST) print(special_form) #Template of form, without values. if form.is_valid() and special_form.is_valid(): return self.form_valid(form, special_form) else: return self.form_invalid(form, special_form) def form_valid(self, form, special_form): product = form.save(commit=False) product.user = self.request.user product.save() special = special_form.save(commit=False) #Here I think, depending on … -
Make an elements list an attribute of the "Groupe" table, where the elements are records (tuples) of the "Etudiant" table
I create a database where one of the attributes of one table must be a list of tuples (record) from another table. I have a "Etudiant" table and a "Groupe" table in my file. How to do it please? Here is an excerpt of the code containing the relevant tables. from django.db import models; from django.contrib.auth.models import User; from django.utils import timezone; # Table qui stockera les groupes aux quelles les étudiants appartiennent class Groupe(models.Model): numero_groupe = models.IntegerField(); nombre_de_membre = models.IntegerField(); liste_etudiant = ; # Here an students list; chef_de_groupe_tp = models.CharField(max_length=100); ue = models.ForeignKey(UE, on_delete=models.PROTECT); date_creation = models.DateTimeField(default=timezone.now, verbose_name="Date de création"); class Meta: verbose_name = "groupe"; ordering = ['date']; def __str__(self): info_groupe = ue.code_ue + " : " numero_groupe; return self.info_groupe; # Table qui stockera les informations concernant les étudiants class Etudiant(models.Model): matricule_etudiant = models.CharField(max_length=10); user = models.OneToOneField(User); # étudiant a désormais les attributs de User. niveau = models.CharField(max_length=10); avatar = models.ImageField(null=True, blank=True, upload_to="avatar/etudiant/"); td = models.ManyToManyField(TD, through='Note_TD'); tp = models.ManyToManyField(TP, through='Note_TP'); class Meta: verbose_name = "étudiant"; ordering = ['matricule_etudiant']; def __str__(self): info_etudiant = matricule_etudiant + " " + user.last_name + " " + user.firstname + " " + niveau; return self.info_etudiant; -
TemplateDoesNotExist at /hello/vscode following Django tutorial documentation
Following the Django tutorial at https://code.visualstudio.com/docs/python/tutorial-django but got an error of TemplateDoesNotExist at /hello/vscode. The error is hello/hello_there.html Request Method: GET Request URL: http://127.0.0.1:8000/hello/vscode Django Version: 2.2 Exception Type: TemplateDoesNotExist Exception Value: hello/hello_there.html Exception Location: C:\Users\v770704\Documents\hello_django\env\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\v770704\Documents\hello_django\env\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\\Users\\v770704\\Documents\\hello_django', 'c:\\Users\\v770704\\.vscode\\extensions\\ms-python.python-2019.3.6215\\pythonFiles', 'C:\\Users\\v770704\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\v770704\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\v770704\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\v770704\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\v770704\\Documents\\hello_django\\env', 'C:\\Users\\v770704\\Documents\\hello_django\\env\\lib\\site-packages'] This is a path issue because the path to hello/templates/hello/hello_there.html is not found, but that path and file do exist. Settings.py has an empty DIRS value, which is what I'm told to use for the DIRS in the tutorial. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] The Template-loader postmortem says: Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\v770704\Documents\hello_django\env\lib\site-packages\django\contrib\admin\templates\hello\hello_there.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\v770704\Documents\hello_django\env\lib\site-packages\django\contrib\auth\templates\hello\hello_there.html (Source does not exist) If I copy the hello/templates/hello folder to the path it's looking in, C:\Users\v770704\Documents\hello_django\env\lib\site-packages\django\contrib\admin\templates, the web page works correctly, so it appears to only be a path-configuration issue. I tried this from another post but get the same error: 'DIRS': [os.path.join(BASE_DIR, "templates")], Even entering the full, literal path to the directory does not work. Thanks in advance … -
How can I change the display name for Django admin filter_horizontal
Assume I have a product object and category object with many-to-many relation. I want to use filter_horizontal to edit them in admin page. How can I change the text display in the form by category object 1 to the text of category except override __str__ in the model? Because I don't want to this change globally. I try to use customer label_from_instance from ModelMultipleChoiceField class, but this will break filter_horizontal. class ProductAdmin(admin.ModelAdmin): filter_horizontal = ['categories'] -
Django i want to breaks when data exists
When I add new years in harvest from YearSet but when year exists I can't breaks it. I try to use exists() but failed. models.py class YearSet(models.Model): year = models.CharField(max_length=4, default='') class Meta: ordering = ["-year"] class Harvest(models.Model): User_id = models.ForeignKey(User, on_delete=models.CASCADE,default='') product = models.IntegerField(default='') years = models.ForeignKey(YearSet, on_delete=models.CASCADE, default='2017') Plant_id = models.ForeignKey(Plant, on_delete=models.CASCADE) -------------------------------------------------------------------------------------- view.py def CreateHarvest(request, Plant_id, Harvest_id, id): if request.method == 'POST': harvestform = addHarvest(request.POST) if harvestform.is_valid(): createharvest = harvestform.save(commit=False) createharvest.user = request.user createharvest.save() return redirect("../../") else: harvestform = addHarvest() harvestcreateform = { 'harvestform': harvestform, } return render(request, 'Farmer/CreateHarvest.html', harvestcreateform) ------------------------------------------------------------------------------ forms.py class addHarvest(forms.ModelForm): class Meta: model = Harvest fields = [ 'product', 'years' ] If Harvest have "2012" don't get exists "2012" -
Partial Keyword Search and Ranking
Using Django and Postgres, I have an investment holding model like so: class Holding(BaseModel): name = models.CharField(max_length=255, db_index=True) symbol = models.CharField(max_length=16, db_index=True) fund_codes = ArrayField(models.CharField(max_length=16), blank=True, default=list) ... That contains a list of approximately 70k US/CAN equity, mutual funds. I want to build an autocomplete search function that prioritizes 1) ranking of exact match of the symbol or fund_codes, followed by 2) Near matches on the symbol, then 3) Full text search of holding name. If I have a search vector that adds more weight to the symbol and fund_codes: from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank from django.db.models import F, Func, Value vector = SearchVector('name', weight='D') + \ SearchVector('symbol', weight='A') + \ SearchVector(Func(F('fund_codes'), Value(' '), function='array_to_string'), weight='A') Then, searching 'MA' Investment.objects \ .annotate(document=vector, rank=SearchRank(vector, query)) \ .filter(document__icontains='MA') \ .order_by('-rank') \ .values_list('name', 'fund_codes', 'symbol', 'rank',) Doesn't give the results I need. I need MA (Mastercard) as top listing, Then MAS (Masco Corp), etc... Then listings containing 'MA' in the name field. I've also looked at overriding SearchQuery with: class MySearchQuery(SearchQuery): def as_sql(self, compiler, connection): params = [self.value] if self.config: config_sql, config_params = compiler.compile(self.config) template = 'to_tsquery({}::regconfig, %s)'.format(config_sql) params = config_params + [self.value] else: template = 'to_tsquery(%s)' if self.invert: template = '!!({})'.format(template) … -
How do I make a function in django to add comments to my reviews
I have a website made on Django and the users able to leave a review and Ive tried to make it so they can add comments, however they add a comment it just saves it to the database rather then adding it to the post. If anyone knows how I could change my code so that it instead adds the comments to the review that they message on rather then them not appearing on the website at all. reviews views.py from django.shortcuts import render, redirect #Render is used to show the HTML, and redirect is used when the user needs to be sent to a different page automatically. from .models import Review #This imports the Review database. from .forms import ReviewForm, CommentForm #This imports the comments and review form. from django.utils import timezone from django.contrib.auth.decorators import login_required #This requires the user to be logged in. def review(request): return render(request, 'review/review.html') @login_required(login_url='/accounts/login/') def review_new(request): if request.method == "POST": form = ReviewForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.date = timezone.now() post.author = request.user post.save() return redirect('/review') else: form=ReviewForm() return render(request, 'review/post_edit.html', {'form': form}) def add_comment_to_post(request): if request.method == "POST": form = CommentForm(request.POST) comment = form.save(commit=False) comment.Review = review comment.save() #This will save … -
Django - How To Make Migrations For Reusable App
I generally use django as a full-blown web app, and am now attempting to make my first pull request on a reusable application. I normally create migrations like this: python manage.py makemigrations Of course, since this is a reusable application there is no manage.py file. Even if I add one, there is no settings.py file to point the manage.py to. What is the accepted way to create migrations for a reusable django application? -
DRF - Raise Exception if any defined field is None
I need to serialize model to JSON. Then send this JSON to one API. But this API requires some fields to be not None. I have a list of these fields. In this case, let's say it's just ['telephone'] but it can be much more. For example: class UserSerializer(serializers.MethodSerializer): telephone = serializers.CharField(source='userprofile.telephone') class Meta: model = User fields = ['first_name','last_name','telephone'] Serialization: >>> UserSerializer(user).data >>> {'first_name':'Michael','last_name':'Jackson','telephone':None} Since API requires some fields like telephone, I want UserSerializer to raise ValidationError when the required field is None. So in this case I couldn't serialize user because telephone is None. I tried many things including adding required=False to the telephone but nothing works. Is there a way to validate serialized data? Note that I'm not talking about deserialization. -
Get details from 2 indexes after joining
What is the elasticsearch query replacing, SELECT * FROM table1, table2 WHERE table1.id = table2.id -
Page Not Found, When i am opening new Page(GET)
Why Get method is throwing , Page not found. I created a new account and when i new form, it says, Page Not foundenter code here def Hfapplication(request): user = request.GET.get("user_id", request.user.id) print(user) host_family = get_object_or_404(hfmodel, pk=user) context = {'exists': True, 'existing_hfmodel': host_family} if request.method=='GET': form =Forms.HFForm(instance=host_family) context['form']=form return render(request, 'hfapplication.html', context) print("hii") elif request.method =='POST': form = Forms.HFForm(data=request.POST, instance=host_family, files=request.FILES) context['form']=form if form.is_valid(): form.save() submit = form.cleaned_data['submitted'] if submit: context['msg]']= "submitted" return render(request,"submittedApp.html", context) context['msg]']= "saved" return render(request, "submittedApp.html", context) this is my view.py where i am getting error -
Can't import my own css file in TINYMCE_DEFAULT_CONFIG = { 'content_css':
As I said in the title I can't import my css file in TINYMCE_DEFAULT_CONFIG variable 'content_css'. I'm using django-tinymce4-lite package and setting 'content_css' in my settings.py file I've tried with the boostrap cdn like this: 'content_css': 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' and it worked but if I do something like this: "content_css": os.path.join(STATIC_URL, "css/style.css") I have the following 404 error: "GET /static/css/style.css HTTP/1.1" 404 1764 my css file is in a static folder located in the root directory of my project like this: /static/css/style.css and my Static conf is: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static/") urls.py urlpatterns = [ path("grappelli/", include("grappelli.urls")), path("admin/", admin.site.urls), path("admin/filebrowser/", site.urls), path("tinymce/", include("tinymce.urls")), path("page/", include("pages.urls")), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) It's been a whole day looking for a solution, even the smallest clue is welcome. Thanks -
The view ... didn't return an HttpResponse object. It returned None instead
I have a view that is throwing me the following error "The view Apps.General.localidades_vistas.Localidad_Crear did not return an HttpResponse object. It returned None instead." when I try to save a new "localidad"... I pass the code to see if you can help me. views.py class Localidad_List(ListView): model = localidades template_name = 'general/localidad_list.html' def get_queryset(self): buscar = self.request.GET.get('buscalo') if buscar: object_list = localidades.objects.filter(localidad__contains = buscar) else: object_list = localidades.objects.all() return object_list class Localidad_Crear(CreateView): model = localidades form_class = LocalidadForm template_name = 'general/localidad_form.html' success_url = reverse_lazy('general:localidad_listar') def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): modelo = form.save(commit=False) modelo.clocalidad = localidad_max() #'99' #print(localidad_max()) usuario = self.request.user modelo.usumodi = str(usuario) form.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('general:localidad_listar') class Localidad_Edit(UpdateView): model = localidades form_class = LocalidadForm template_name = 'general/localidad_form.html' success_url = reverse_lazy('general:localidad_listar') class Localidad_Delete(DeleteView): model = localidades template_name = 'general/localidad_delete.html' success_url = reverse_lazy('general:localidad_listar') def localidad_max(): try: cvalor = localidades.objects.latest('clocalidad').clocalidad except: cvalor = '0' cvalor = str(int(cvalor) + 1) return cvalor.zfill(5) def provincia_load(request): cpais = request.GET.get('cpais') xprovincias = provincias.objects.filter(cpais = cpais).order_by('provincia') return render(request,'general/combo_provincia.html', {'provincias':xprovincias}) urls.py from .views import from .localidades_vistas import Localidad_List, Localidad_Edit, Localidad_Delete, Localidad_Crear, provincia_load #, Provincia_Crear, Provincia_Edit, Provincia_Delete app_name = 'general' urlpatterns = [ path('',index, name = 'index'), #--------------------- Localidades --------------------------- path('localidades',Localidad_List.as_view(), … -
Django Tagulous - * needs to be saved before TagField can use the database
I'm creating a django project with tagulous. When I try to save my model I always get this error: ValueError: "myModel" needs to be saved before TagField can use the database that's my TagField: tags = tagulous.TagField(force_lowercase=True, max_count=10) I really dont know whats the problem. Is it because I'm using PostgreSQL? -
'User' object has no attribute 'profile'
I have created a separate user profile app for an app am working following this tutorial https://thinkster.io/tutorials/django-json-api/profiles so I want the profile to be updated at the same time as the password or username so I created my models in profiles/models.py and I just import it to the authentication model. According to the tutorial, it should work but I keep on getting this error. Let me share my authentication/serializers.py class LoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) username = serializers.CharField(max_length=255, read_only=True) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): # The `validate` method is where we make sure that the current # instance of `LoginSerializer` has "valid". In the case of logging a # user in, this means validating that they've provided an email # and password and that this combination matches one of the users in # our database. email = data.get('email', None) password = data.get('password', None) # As mentioned above, an email is required. Raise an exception if an # email is not provided. if email is None: raise serializers.ValidationError( 'An email address is required to log in.' ) # As mentioned above, a password is required. Raise an exception if a # password is not provided. if … -
Django ModelForm doesn't Work with Decimal Field
I have a Django model with a DecimalField like so: CHOICES = [ ("0.1", "0.1"), ("0.2", "0.2"), ("0.3", "0.3"), ... ] class MyModel(Model) field = models.DecimalField(max_digits=10, default="1.0", decimal_places=1, choices=CHOICES) I then have a ModelForm class MyForm(ModelForm): class Meta: model = MyModel exclude = [] When I try to save the form, I get the following error: Select a valid choice. 0.1 is not one of the available choices. "0.1" is in my choices. What is wrong with my setup? -
Which nginx load balancing method should I use for my Django app?
I'm new to load balancing and need to design a load balancing to cope with high load on my Django app. The app includes registered user activities and currently the sessions are saved in server A's redis. Now I'd like to add a server B, which is half as powerful as server A and will contain a colone of the app currently running on the server A. The server A is behind cloudflare and will server the upstream. I'm using free nginx and I understand how are roundrabin, laeas_conn, ip_hash and weighted method work to distribute loads, but I'm not sure which one (or combination of them?) suite my use case. So appreciate your hints. -
Django Rest Framework - make fields required
I'm using DRF to serialize objects to export them through API, I don't use it to creating objects. Looking for a simplest way to make fields required in context of the API. The API needs some fields to be not null so I want to raise APIMissingDataException. I tried: class Meta: model = User fields = ['import_id', 'deleted', 'full_name', 'phone_work', 'email_work'] required_fields = fields def validate(self, attrs): super().validate(attrs) if not all([attrs.get(fieldname) for fieldname in self.Meta.required_fields]): raise APIMissingDataException() But validate function is not being called for some reason. I don't want to explicitely defining all fields just to add required=False parameters to them. Is there a more comfortable way? -
Why do new media files appear by themselves in my django application?
I have recently added new ImageField to my Bird model in Django application. # models.py class Bird(models.Model): name = models.CharField(max_length=50) project = models.ForeignKey( Project, related_name='birds', on_delete=models.CASCADE ) def bird_images_path(instance, filename): return 'bird_images/' + instance.project.directory + '/' + filename image = models.ImageField(upload_to=bird_images_path, null=True, blank=True) In django admin I have added new records to Bird table in db, uploaded images and they appered in my media path (\media\tag_images\birds) as expected. Everything worked well. Nevertheless, after some time some weirdly named copies of my previous files appeared in the same location. For example, dove_ee9rsOT.jpg and dove_zRCwQrj.jpg are now saved next to originally uploaded dove.jpg. All three images are identical and the database record contains one of the new ones. However, I don't recall adding any such images and nobody else has access to my app. Is there any explanation for this behavior or a way how to prevent it? -
type object 'Notification' has no attribute 'object'
I get this error from my view.py type object 'Notification' has no attribute 'object' and my view.py from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from notification.models import Notification def show_notification(request, notification_id): n = Notification.object.get(id=notification_id) return render_to_response('notification.html', {'notification':n}) def delete_notification(request, notification_id): n = Notification.object.get(id=notification_id) n.viewed = True n.save() and also my models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Notification(models.Model): title = models.CharField(max_length=250) message = models.TextField() viewed = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) def create_welcome_message(sender, **kwargs): if kwargs['created']: noti=Notification.objects.create(user=kwargs['instance'], title="Welcome Message", message="Thank you for singing up!") post_save.connect(create_welcome_message, sender=User) I've been missing for a long time. using this language. then help me with this error -
How to save calculated variables in django database and load it after?
I'm making a simple calculation app, but i want to save calculated variables in the database so I can load them after i need them.Thank you def showvideo(request): allvideos = Video.objects.all() form = VideoForm(request.POST or None) if form.is_valid(): sirina = form.cleaned_data.get('sirina') visina = form.cleaned_data.get('visina') category = form.cleaned_data.get('category') roletne = form.cleaned_data.get('roletne') okapnice = form.cleaned_data.get('okapnice') materijal = form.cleaned_data.get('materijal') komore = form.cleaned_data.get('komore') krila = form.cleaned_data.get('krila') #Example a = 20 + sirina b = 30 + visina c = 50 + roletne ## I want to save those variables in database and load them after ## in template form.save() context={'form':form} return render(request,'index.html',context) -
Django admin showing object ID instead of __str__ when deleting
I'm not sure if this is a bug, by design or something I've done. I'm seeing the same issue as this issue when deleting an item with a M2M relationship where the object ID is returned instead of str. The str is set correctly and displays correctly otherwise, just not when deleting an item. The object ID shows up instead. I've tested by creating a new Django project and a simple model with 2 classes related by M2M but get the same thing. The only way I've found, which isn't ideal, is to use the "through" option on the field. One I have many relationships like this in various models. Two, returning str on the intermediate model I have to display both fields so that it makes sense when deleting from either of the related models. Anyone have any thoughts? Is using "through" the only option? -
How to drop dataframe column(s) after clicking on a link button?
I'm trying to delete a specific dataframe column. My problem is how can I call a function from the template and re-render the same template after dropping the column. I've tried creating another view to handle the dropping of the column. But could not able to figure out how to actually execute the dropping of the specified column. This is my template where the columns are selected for dropping (preprocess.html): <tbody> {% for key in n_cols %} <tr> <td>{{ key }}</td> <td align="right">{% get_key_count df key %}</td> <td align="right">{% get_missing df key %}</td> <td align="right">{% get_missing_rows_percent df key %}</td> <td class="text-center"> <a href="#" class="btn btn-info btn-sm"> <i class="fas fa fa-pencil fa-cog"></i> </a> </td> <td align="right" class="text-center"> <a href="{% delRowsMissingView project.id df key %}" class="btn btn-warning btn-sm"> <i class="fas fa-trash fa-cog"></i> </a> </td> <td class="text-center"> <a href="#" data-q_id="{{ key }}" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#delMissingColModal"> <i class="fas fa-trash fa-cog"></i> </a> </td> </tr> Here the view that facilitates the rendering of the template: class PreprocessView(DetailView): model = Project context_object_name = 'projects' template_name = 'projects/preprocess/preprocess.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) project = self.get_object() try: df = pd.read_csv(project.base_file) except: pass context['project'] = project context['df'] = df context['n_cols'] = df.keys return context The underlying … -
Page not found, django.urls
Django-version 2.1.2. I am trying to call a function in my views.py by pasting a url in the web browser. When I put "http://127.0.0.1:8000/upload_results/UniEX_HG1_A15" I do not get an answer. I can not see why my URL pattern does not work. This already worked some time ago, but in the meantime I did many changes. Latest change was to include celery (djcelery). The index page and others still work. Here is the message from the web browser: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/upload_results/UniEX_HG1_A15 Using the URLconf defined in varview.urls, Django tried these URL patterns, in this order: ^$ [name='show_index'] ^admin/ ^upload/ [name='varview_submission'] ^upload_results/(?P<project_id>[0-9A-Za-z_]+)/ [name='varview_upload_results'] ^validate/(?P<project_id>[0-9A-Za-z_]+)/ [name='varview_validate'] ^filterallprojects/[0-9A-Za-z_]+ [name='varview_filterallprojects'] ^project/(?P<project_id>[0-9A-Za-z_]+)/wgsmetrics/ [name='varview_wgsmetrics'] ^project/(?P<project_id>[0-9A-Za-z_]+)/targetgenecoverage/ [name='varview_targetgenecoverage'] ^project/(?P<project_id>[0-9A-Za-z_]+)/(?P<display_option>[0-9A-Za-z_]+)/ [name='varview_project'] ^media\/(?P<path>.*)$ The current path, upload_results/UniEX_HG1_A15, didn't match any of these. And here is my urls.py: from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from django.contrib import admin from varview import views from varview.forms import DataUploaderForm1, DataUploaderForm2, GetProjectIdForm urlpatterns = [ url(r'^$', views.show_index, name='show_index'), url(r'^admin/', admin.site.urls), url(r'^upload/', views.init_submission, name='varview_submission'), url(r'^upload_results/(?P<project_id>[0-9A-Za-z_]+)/', views.upload_results, name='varview_upload_results'), ] I already read many posts related to django-url, but could not figure it out. Thank you for your help. -
Python - Django add multiple urlpatterns for multiple views of template
I'm very very new to Python 3 and Django and I get to the following problem: I use a standard Template and now how to set it up when there is 1 view. But I don't get the code right for multiple views. I currently run the page locally At the moment I have tried to change different orders within urlpatterns, and they do work when only 1 url in in there, but I can't get the second one in views.py from django.shortcuts import render, render_to_response # Create your views here. def index(request): return render_to_response('index.html') def store(request): return render_to_response('store.html') urls.py from django.conf.urls import include, url from django.contrib import admin from myapp import views as views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^store/$', views.store, name='store'), url(r'^admin/', admin.site.urls) ] urlpatterns += staticfiles_urlpatterns() I would like the url pattern that lets me go to the index view and the store view