Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tabula-py split row depending on the condition
I have a csv like below and i want to split rows base on header 2 and 3, how can i do that in tabula-py? sample csv below is the code i used in converting from pdf to csv then i am displaying it in html table tabula.convert_into("PDFTest_index\static\\test.pdf", "PDFTest_index\static\\output.csv", output_format="csv", pages='all',lattice=True, stream=True) df = pd.read_csv('PDFTest_index\static\\output.csv') df.columns = df.columns.str.replace(' ', '') json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'d': data} I have no idea, on how to do this in python tabula -
HTML table not fetching data from Django only showing heading
I'm using HTML, CSS, and Javascript for the frontend and Django for the backend, and PostgresSQL for DB. Actually, I have successfully loaded data from the EXCEL file to Django and I'm trying to fetch data from Django to HTML Table. But, I'm getting only headers of the table, not the data. How to fix it. index.html {%extends "base.html"%} {%block content%} <html> <table> <thead> <th>Brand</th> <th>Name</th> </thead> <tbody> <tr> <td><strong>{{pro.brand}}</strong></td> <td><strong>{{pro.name}}</strong></td> </tr> </tbody> </table> {%endblock%} views.py def product(request): pro = Product.objects.all() return render(request, 'index.html',{'pro': pro}) urls.py (App file) urlpatterns = [ path('product/', views.product, name='product'), ] -
Annotation syntax error when migrating from 2.2.x to 3.x
I am in the process of migrating from Django 2.2 to 3.2. After fixing most deprecation issues, an annotation I rely on throughout my project is throwing a syntax error. It does not appear to matter which 3.x version I use, and this annotation has worked throughout most of 2.2.x's versions: Journal.objects.annotate( p_user=F('assignment__courses__participation__user'), can_have_journal=F('assignment__courses__participation__role__can_have_journal'), ).filter( Q(assignment__is_group_assignment=True) | Q(p_user__in=F('authors__user'), can_have_journal=True), ) This yields the following error: django.db.utils.ProgrammingError: syntax error at or near ""VLE_assignmentparticipation"" LINE 1: ...ave_journal" AND "VLE_participation"."user_id" IN "VLE_assig... Part of the trace: venv/lib/python3.8/site-packages/django/db/models/query.py:317: in __getitem__ qs._fetch_all() venv/lib/python3.8/site-packages/django/db/models/query.py:1324: in _fetch_all self._result_cache = list(self._iterable_class(self)) venv/lib/python3.8/site-packages/django/db/models/query.py:51: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py:1169: in execute_sql cursor.execute(sql, params) venv/lib/python3.8/site-packages/sentry_sdk/integrations/django/__init__.py:434: in execute return real_execute(self, sql, params) venv/lib/python3.8/site-packages/django/db/backends/utils.py:66: in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) venv/lib/python3.8/site-packages/django/db/backends/utils.py:75: in _execute_with_wrappers return executor(sql, params, many, context) venv/lib/python3.8/site-packages/django/db/backends/utils.py:84: in _execute return self.cursor.execute(sql, params) venv/lib/python3.8/site-packages/django/db/utils.py:90: in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value For good measure a link to the models file If I eliminate the or in the filter block: | Q(p_user__in=F('authors__user'), can_have_journal=True), the annotation works without issues. I cannot find anything in the release/deprecation notes about annotations changing, does anyone have a recommendation on what the underlying issue could be? -
500 Internal server error "populate() isn't reentrant"
I am having issues with deploying some recent work on a Django app to my server. On deployment, I updated a few pip modules, and there was also some restructuring of the directories. Once done, I restarted apache2, but was greated by the below error messages which proved unhelpful [Thu May 13 13:12:09.846428 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] mod_wsgi (pid=8385): Target WSGI script '/var/www/stage.admin.agile.coop/web/mysite/wsgi.py' cannot be loaded as Python module. [Thu May 13 13:12:09.846751 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] mod_wsgi (pid=8385): Exception occurred processing WSGI script '/var/www/stage.admin.agile.coop/web/mysite/wsgi.py'. [Thu May 13 13:12:09.847024 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] Traceback (most recent call last): [Thu May 13 13:12:09.847174 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] File "/var/www/stage.admin.agile.coop/web/mysite/wsgi.py", line 16, in <module> [Thu May 13 13:12:09.847275 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] application = get_wsgi_application() [Thu May 13 13:12:09.847363 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] File "/var/www/stage.admin.agile.coop/venv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Thu May 13 13:12:09.847460 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] django.setup(set_prefix=False) [Thu May 13 13:12:09.847561 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] File "/var/www/stage.admin.agile.coop/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup [Thu May 13 13:12:09.847655 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] apps.populate(settings.INSTALLED_APPS) [Thu May 13 13:12:09.847755 … -
UnboundLocalError:local variable 'final_result' referenced before assignment..django
I am a beginner in Programming and Django. I am making a calculator. but I am getting an error(UnboundLocalError:local variable 'final_result' referenced before assignment).The code is from django.http import HttpResponse from django.shortcuts import render import re def clculator(request): pass def calculation(request): if request.method == "POST": values = request.POST['values'] print(values) vals = re.findall(r"(\d+)", values) operators=['+','x','÷','-','.','%'] opr = [] for v in values: for o in operators: if v == o: opr.append(o) print(opr) print(re.findall(r"(\d+)", values)) for o in (opr): if o=='.': i=opr.index(o) res=vals[i]+"."+vals[i+1] vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=res print(vals) print(opr) for o in opr: if o == '%': i = opr.index(o) res =(float(vals[i])/100)*float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]= res print(vals) print(opr) for o in opr: if o == '÷': i = opr.index(o) res = float(vals[i])/float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i] = str(res) print(vals) print(opr) for o in opr: if o == 'x': i = opr.index(o) res = float(vals[i])*float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i] = str(res) print(vals) print(opr) for o in opr: if o == '+': i = opr.index(o) res = float(vals[i])+float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i] = str(res) print(vals) print(opr) for o in opr: if o == '-': i = opr.index(o) res = float(vals[i])-float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i] = str(res) print(vals) print(opr) if len(opr) != 0: if opr[0] == '÷': result = float(vals[0])/float(vals[1]) … -
Django's validation level
I have a model level validation: class MyModel(models.Model): # some fields def clean(self): pass But how can I get a request.user in clean method so the model to be validated as via django's default admin forms as via views (REST api)? Or what is the best practice in which level to validate: Model, ModelForm, Serializer, View? -
How can I populate a form field from a list of elements in JavaScript?
I've got a fantasy football project that I built in Django that generates a list of HTML elements. Like this... <tbody id="page1"> {% for q in QBpage %} <tr> <td><h6 id="qbname">{{ q.player_name }}</h6></td> <td><button onclick="selectPlayer()" type="button" id="qbackbutton" class="btn btn-success btn-sm m-0 waves-effect" data-player-name="{{ q.player_name }}" data-position="{{ q.position }}">Add</button></td> <td><h6> {{ q.team }} </h6></td> <td><h6> {{ q.position }} </h6></td> <td><h6>{{ q.points }}</h6></td> </tr> {% endfor %} </tbody> It's a list of players (all quarterbacks) pulled from an API. What I'm trying to do is from each player's corresponding "Add" button, is add that player's name to a form field that's also on the same page. I can do that using this JavaScript function... function selectPlayer (){ let d = document.getElementById("qbname"); document.getElementById("QB_name").value = document.getElementById("qbname").innerHTML; } Problem is though, I can only get the name of the first player in the list because all players end up with the same id. Therefore, you can only retrieve the first element. Even if I click on a player further down the list, that first player's name is the only one that is returned. Assigning a class won't work because, as far as I understand, you can only "getElementsByClass" so you end up retrieving all the … -
Django and pytest, multiple databases, use only one database
I have 2 databases in my project: DATABASES = { 'default': env.db('DEFAULT_DATABASE_URL'), 'second': env.db('SECOND_DATABASE_URL'), } When I had only one database, then all tests that required access to the database passed fine, but when I connected the second one, then all tests began to fail with an error - django.db.utils.IntegrityError: duplicate key value violates unique constraint. As I understand it, the test runs twice for each database and crashes because of this. Is there some way to tell pytest to only take one database for tests? Example of one test: @pytest.mark.django_db def test_complaint_reasons(client: APIClient): reasons_count = 12 Profile.create_batch(reasons_count) client.force_login(Factory()) response = client.get(reverse('url')) assert response.status_code == status.HTTP_200_OK assert len(response.data) == reasons_count jsonschema.validate(response.data, ProfileComplaintReasonsSchema) -
Django global ManyToMany Relation (more than symmetrical)
I have trouble on how to make a ManyToMany relation where every object is connected to every other object. Here's my example for better understanding: class Animal(models.Model): animaux_lies = models.ManyToManyField("self", verbose_name="Animaux liés", blank=True) If y have only two animals linked together, it works fine, thez I correctly linked together in both ways (because the relation is symmetrical). But if I have 3 or more animals, I don't get the result I want. If Animal1 is linked to Animal2 and Animal3, I would like Animal2 to not only be linked to Animal1 but also to Animal3 (and Animal3 linked to 1 and 2). How can I do that? Even with a through table I don't see how to do this correctly -
Django abstract model with indices, constraints and permissions: attributes are not inherited by sub classes
I am using Django 3.2 I have the following models: app1 class IsPinnable(models.Model): is_pinned = models.BooleanField(default=False) pin_after_expiry_day_count = models.DurationField(default=0) class Meta: abstract = True indexes = [ models.Index(fields=['is_pinned' ]), ] class IsModeratable(models.Model): approved = models.BooleanField(default=False) target_count_trigger = models.PositiveSmallIntegerField() positive_pass_count = models.PositiveSmallIntegerField(default=0) negative_pass_count = models.PositiveSmallIntegerField(default=0) # Other fields and methods ... def save(self, *args, **kwargs): # TODO: Sanity check on pass_count and trigger sizes # ... super().save(*args, **kwargs) class Meta: abstract = True permissions = ( ("moderate_item", "can moderate item"), ("reset_moderation", "can (re)moderate a moderated item"), ) indexes = [ models.Index(fields=['approved' ]), ] class MyComponent(IsPinnable, IsModeratable): # some fields and methods ... class Meta(IsPinnable.Meta, IsModeratable.Meta): abstract = True # other stuff ... app2 from app1.models import MyComponent class Foo(MyComponent): # some fields and methods ... class Meta(MyComponent.Meta): abstract = False Now, I know that abstract model classes are not created in the database - so I was initially expecting Django to throw an exception when I attempted to makemigrations - to my surprise, I was able to makemigrations && migrate. However, when I inspected the database (via psql), I found that although table app2_foo had all the fields described in it's parent class, the indixes were not being carried up from … -
Reverse for 'signup' not found. 'signup' is not a valid view function or pattern name [closed]
code I'm getting Reverse for 'signup' not found. 'signup' is not a valid view function or pattern name. -
Variable dictionary in django using javascript
I am passing a dictionary of variable size to an html, and in the html I have a script (javascript) that I need to make one for inside another. And by the code you can get a sense of what I need. I need to pass every "Exame" to especific "Cliente". HTML file: <p id="dependentes"></p> {% for obj in object3 %} <div> <ul><p>Exames de {{ obj.id_cliente1 }}: </p> <div id="iteracao"></div> </ul> </div> <script type="text/javascript"> var cliente1 = "{{ obj.id_cliente1 }}"; var teste = document.getElementById('teste'); cliente2 = teste.value; cliente2 = cliente2.replace(" ", "_"); document.getElementById('iteracao').textContent = "\{\% for obj2 in " + cliente2 + " \%\}" + "<li><a href='/exames/\{\{ obj2.slug \}\}/'>\{\{ obj2.nome \}\}</a></li>" + "\n" + "\{\% endfor \%\}"; //JSON.parse(document.getElementById('iteracao').textContent); var a = document.getElementById('dependentes`enter code here`'); if (cliente1 != "None"){ a.innerHTML = "Dependentes: "; } </script> {% endfor %} View file: class ClienteDetailView(DetailView): def get_queryset(self): self.slug = self.kwargs.get("slug") if self.slug: queryset = Cliente.objects.filter(slug__icontains=self.slug) else: queryset = Cliente.objects.all() print('ClienteDetailView') return queryset #, queryset2 #, queryset3, queryset4 def get_context_data(self, **kwargs): queryset = Cliente.objects.filter(slug__icontains=self.slug) cliente = Cliente.objects.get(slug__icontains=self.slug).id_cliente queryset2 = Exame.objects.filter(cliente_fk=cliente) queryset3 = Dependencia.objects.filter(id_cliente2=cliente) quantidade = Dependencia.objects.filter(id_cliente2=cliente).count() context = { "object": queryset, "object2": queryset2, "object3": queryset3, } if quantidade > 0: for i in queryset3: #cliente2 … -
django Rest frame work : token authentication
I have a table ('like') to like post class Likes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() i have a table course : class Courses(models.Model): title = models.CharField(max_length=100, null=True) description = RichTextUploadingField(null=True) like = GenericRelation(Likes) i use restman opera extension to send POST request to my api if i login with browser i get error "detail": "CSRF Failed: CSRF token missing or incorrect." but i use restman only(i dont login with browser) every thing is OK setting.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication' ] } -
Can't access a variable from django views.py to html pqge
I know you can show a variable from the views.py using the {{variable_name}} But my variable name is in a if statement: So even when I type {{variable_name}} it doesn't show. Rather it gets the else statement: variable_name = '' What could be the cause,m -
next or previous item within an ordered, filtered queryset in Django
How can I make transitions to the next article from the post_details(DetailView), so that both the next article and the previous one are available ? vievs.py class HomeView(ListView): model = Post #queryset = Post.objects.filter(status=1) cats = Category.objects.all() template_name = 'home.html' #ordering = ['-post_date'] paginate_by = 6 def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(HomeView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context class ArticleDetailView(HitCountDetailView): model = Post template_name = 'post_detail.html' count_hit = True def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(ArticleDetailView, self).get_context_data(*args, **kwargs) stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() context["cat_menu"] = cat_menu context["total_likes"] = total_likes return context Sort by date and ID -
Django changing template_name in get_context_data dynamically
how do I override the template_name of a TemplateView based on the context in get_context_data? In other words, I would like to find a way to change the template rendered according to my context. The following is modified from my current code and it does not work: class FooPage(TemplateView): template_name = "folder/template1.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['myvariable'] = MyModel.objects.get(pk=kwargs['some_criterion']).variable if "text" in context['myvariable']: template_name = "folder/template2.html" # This line does get executed return context I can confirm that the line changing template_name is executed and it is indeed set to "folder/template2.html" at that point, but the actual page that gets rendered still looks like the original (template1.html) instead. Any helpful insight would be deeply appreciated. Thank you very much! -
Saving Multiple Objects from same Form - 'QuerySet' object has no attribute '_meta' Django
I am creating a post which will have gallery images, Views.py def tripUpdate(request, pk): trip = get_object_or_404(Trip, pk=pk) trip_images = TripImages.objects.filter(trip=trip).first() trip_form = AddTripForm(request.POST or None, request.FILES or None, instance=trip) trip_image_form = AddTripImageForm(request.POST or None, request.FILES or None, instance=trip_images) if request.method == 'POST': if trip_form.is_valid() and trip_image_form.is_valid(): trip_form.save() images = request.FILES.getlist('image') for photo in images: i = TripImages.objects.create( trip=Trip.objects.get( title=trip_form.cleaned_data['title']), image=photo, ) messages.success(request, 'Trip Updated') return redirect('dashboard') Models.py class Trip(models.Model): title = models.CharField(max_length=255, unique=True) fields.... class TripImages(models.Model): trip = models.ForeignKey( Trip, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField( upload_to='trip-images/%Y/%m/%d', null=True, blank=True) I am creating Trip and TripImages in same form, While uploading TripImages.image i use multiple file upload While updating i get the error 'QuerySet' object has no attribute '_meta' I want to get all the TripImages which i have uploaded for the particular Trip, .filter(trip=trip).first() only returns single image and only using .filter(trip=trip) gives the above error but i want all the images to show, How can i do that, Thank You! -
get student id when storing student mark -Django
im creating a small student management app using django, i wanna know how to get the student_id in student table to student_mark table without using GET request(when i clicked add marks) -
Dash App with Django gives an error of NolayoutExeption even though everthing seems to be correct
This is the dast app code file capi and ceda are jupyter notebooks downloaded and I am calling a function from the file import dash import dash_table import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go from django_plotly_dash import DjangoDash #import for dash file from website.dash_app import coronaAPI1 as capi from website.dash_app import CoronaEDA2 as ceda from flask import send_from_directory app1 = DjangoDash('india_plot') ################################################################### #######figure 1 ################# app1.layout = html.Div(style={"background-color":"rgb(17, 17, 17)"}, className='card', id='main-div', children=[ html.Br(), html.Div(className='card', id='div1', style={'text-align': 'center'}, children=[ dcc.Dropdown(className='dropdown',id='dropdown-1', options=[ {'label': 'Confirmed Cases', 'value':'confirmed'}, {'label': "Recovered Cases", 'value': 'recovered'}, {'label': "Deceased Cases", 'value': 'deaths'}, {'label':'Active Cases', 'value':'active'}, ], value='confirmed', ), html.Br(), dcc.Graph(id='india_map'), ]), ]) @app1.callback( Output('india_map', 'figure'), [Input('dropdown-1', 'value')] ) def figure1(status): return capi.india_cases(status) ################################################################# #########figure 2 ######################### app2 = DjangoDash('total_cases_india_line_graph') total_cases_india = ceda.total_cases_india() app2.layout = html.Div(className='card', children=[ html.Br(), html.Div(className='card', id='div1', style={'text-align': 'center'}, children=[ html.Br(), dcc.Graph(figure=total_cases_india), ]), ]) ######################################################### #################figure 3 ###################### app3 = DjangoDash('daily_cases') app3.layout = html.Div(className='card', id='main-div1', children=[ html.Br(), html.Div(className='card', id='div4', style={'text-align': 'center'}, children=[ html.H2(id='heading3', children=[ "Vizualization of India based on specific conditions of COVID-19 Cases Reported." ]), dcc.Dropdown(className='dropdown',id='dropdown-2', style={ 'width':'200px', # 'background-color':'rgba(70, 70, 70, 0.6)', # 'color':'black', }, optionHeight=35, options=[ {'label': 'Confirmed Cases', 'value':'dailyconfirmed'}, {'label': "Recovered … -
How to design relationship betwen these django models?
I have to make this Django Rest Framework API which can book Advisors from the available lists of advisors through the specific endpoint user/<user-id>/advisor/<advisor-id> Models i have(models.py) : #User class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' #Advisor class Advisor(models.Model): """Advisor object to be booked""" name = models.CharField(max_length=255) image = models.ImageField(upload_to=advisor_image_file_path) def __str__(self): return self.name #Booking class Booking(models.Model): """Booking the Advisor""" advisor = models.ForeignKey( Advisor, default = '' , on_delete = models.CASCADE ) date_time_field = models.DateTimeField(auto_now_add=False, auto_now=False) user = models.ForeignKey( User, on_delete = models.CASCADE, default = 1 ) def __str__(self): return "{}".format(self.date_time_field) I don't know if this logic is correct or not but i am getting error core.booking has no column advisor_id If this is not the correct logic, please suggest the correct one. -
How to use foreign key field in unique_together to validate?
I trying to make tournament_date, tournament_time and match_type must be unique entry. tournament_date and match_type is in MTournament table tournament_time is in Mtournament_Time table This how I implement unique_together in Mtournament_Time table. unique_together = ['mtournament__tournament_date', 'mtournament__match_type', 'tournament_time'] class BaseClass(models.Model): is_active insert_date updated_date class Game(BaseClass): # is_active, insert_date, updated_date # name, game_image name = models.CharField(max_length=16) game_image = models.ImageField(upload_to='game_images/', default='game_images/game_default.jpg') class GameMap(BaseClass): # is_active, insert_date, updated_date game = models.ForeignKey(Game, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=64) class Tournament(BaseClass): CHECK = ( ("No", "NO"), ("Yes", "YES"), ) MATCH_TYPE = ( ("Solo", "SOLO"), ("Duo", "DUO"), ("Squad", "SQUAD"), ) # is_active, insert_date, updated_date # game, name, tournament_date, map, match_type, camera_type, country, country_base game = models.ForeignKey(Game, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=64) tournament_image = models.ImageField(upload_to='esports/tournament', default='esports/user/default.png') country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, default=99) country_base = models.CharField(choices=CHECK, max_length=8, default='NO') class MTournament(BaseClass): MATCH_TYPE = ( ("Solo", "SOLO"), ("Duo", "DUO"), ("Squad", "SQUAD"), ) # is_active, insert_date, updated_date # tournament, mtournament_date, map, match_type tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) tournament_date = models.DateField(verbose_name='Tournament Date') map = models.ForeignKey(GameMap, on_delete=models.SET_NULL, null=True) match_type = models.CharField(choices=MATCH_TYPE, max_length=32, default=1) class Mtournament_Time(BaseClass): # is_active, insert_date, updated_date mtournament = models.ForeignKey(MTournament, on_delete=models.SET_NULL, null=True) tournament_time = models.TimeField(verbose_name='Multiple Tournament Time') class Meta: db_table = 'tbl_mtournament_time' verbose_name = "Tournament Time" # Below is the code i want … -
Export a list of customers who completed registration but haven't performed any action (no invoice, expense, withdrawal)
This is the full task : Export a list of customers who completed registration but haven't performed any action (no invoice, expense, withdrawal) last week (3-9 May) I need to create this type of SQL, but I don't know how to check for actions, what I did for now is SELECT user FROM users_user WHERE completed_registration=False AND date_joined BETWEEN '2021-05-03 00:00:00' AND '2021-05-29 00:00:00' UNION SELECT user FROM invoice_invoice; Check for users who had completed the registration, check for the date, and then check the invoice. But as I check for invoice_invoice itself it's an empty table, why do I get one user when I launch this query? The completed_registration and the date fields which are in queryset right now are only for test. Only users This is when I check only for invoices This is the structure: Expense model: class Merchant(BaseModel): company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name='merchants') name = models.CharField(max_length=255) company_code = models.CharField(max_length=255, default='', blank=True) def __str__(self): return f'{self.company} {self.name}' class Expense(Operation): category = models.CharField(choices=ExpenseCategories.get_choices(), default=ExpenseCategories.GENERAL.name, db_index=True, blank=True, max_length=255) merchant = models.ForeignKey(Merchant, on_delete=models.PROTECT, related_name='expenses', blank=True, null=True) amount = models.PositiveIntegerField(default=0, blank=True, help_text='Only taxable amount. In cents') full_amount = models.PositiveIntegerField( default=0, blank=True, help_text='Full amount. Most of the time same as amount or … -
Login alone is not working in django...I want what is wrong [closed]
the picture has the code that I have been used for login view which not working -
NoReverseMatch Error but couldn't find its source
I am relatively new to Django and started to create my first To-Do-List. However I get an error whenever I try to create an href that says: NoReverseMatch at /aufgabenzettel/ I have desperately tried to fix it for the last five hours and am very frustrated because the error just seems to be caused by a single line of code... Please help! It would be awesome and I really appreciate every hint! Here's the code: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:aufgabenzettel_id>", views.details, name="details") ] views.py from django.shortcuts import render from .models import Aufgabenzettel # Create your views here. def index(request): return render(request, "aufgabenzettel/index.html", { "Aufgabenliste":Aufgabenzettel.objects.all() }) def details(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) return render(request, "aufgabenzettel/details.html", { "details":aufgabenzettel }) models.py from django.db import models # Create your models here. class Aufgabenzettel(models.Model): Aufgabeselbst = models.CharField(max_length=64) def __str__(self): return f"{self.Aufgabeselbst}" layout.html <!DOCTYPE html> <html lang="de"> <head> <title>Aufgabenzettel</title> </head> <body> {% block body %} {% endblock %} </body> </html> index.html {% extends "aufgabenzettel/layout.html" %} {% block body %} <h1>Meine Aufgaben</h1> <ul> {% for Aufgabeselbst in Aufgabenliste %} <li> <a href="{% url 'details' aufgabenzettel.id %}"> Aufgabe {{ Aufgabeselbst }} </a> </li> {% endfor %} </ul> … -
Only one row is added from 2000+ rows in excel, while uploading it into django admin
I have around 2000+ row in my excel file and while uploading the selected files its show only last row added to the Django admin. How to fix it? Here is my import.html(HTML FILE) {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% endblock %} views.py def simple_upload(request): if request.method == 'POST': product_resource = ProductResource() dataset = Dataset() new_product = request.FILES['myfile'] if not new_product.name.endswith('xlsx'): messages.info(request,'Wrong Format') return render(request, 'Upload.html') imported_data = dataset.load(new_product.read(),format='xlsx') for data in imported_data: value = Product( data[0], data[1], data[2], data[3], data[4], data[5], data[6] ) value.save() return render(request,'import.html') resources.py from import_export import resources from .models import Product class ProductResource(resources.ModelResource): class Meta: model = Product admin.py admin.site.register(Product) class PersonAdmin(ImportExportModelAdmin): pass urls.py urlpatterns = [ path('',views.simple_upload), ]