Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'anhangdelete' with arguments '('',)' not found. 1 pattern(s) tried: ['Verwaltung/AnhangDelete/(?P<id>[0-9]+)$']
Error: Request Method: GET Request URL: http://127.0.0.1:8000/Verwaltung/Anhang/10 Django Version: 3.0.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'anhangdelete' with arguments '('',)' not found. 1 pattern(s) tried: ['Verwaltung/AnhangDelete/(?P[0-9]+)$'] Exception Location: C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\Scripts\python.exe Python Version: 3.8.0 views.py @login_required() def anhang_view(request, id=None): contextoo = {} item = Kunden.objects.get(id=id) kontaktform_form = KontaktForm(request.POST or None, instance=item) creatorform_form = CreateANform() contextoo['creatorform_form'] = creatorform_form if Kunden.objects.filter(KN=item.KN).exists(): item14 = Kunden.objects.get(KN=item.KN) editkontakto_form = InfoKontaktoForm(request.POST or None, instance=item14) contextoo['editkontakto_form'] = editkontakto_form if Anhang.objects.filter(KN=item.KN).exists(): item15 = Anhang.objects.filter(KN=item.KN) contextoo['ANform_form'] = item15 if request.method == 'POST': creatorform_form = CreateANform(request.POST) if creatorform_form.is_valid(): cre = creatorform_form.save(commit=True) cre.save() return redirect('/Verwaltung/KontaktAnlegen') else: return render(request, 'blog/anhang.html', contextoo) @login_required() def AnhangDeleteView(request, id): anh = Anhang.objects.get(id=id) anh.delete() return redirect(reverse('blog:Anhang')) urls.py path('AnhangDelete/<int:id>', views.AnhangDeleteView, name='anhangdelete'), anhang.html . . . {% if ANform_form %} {% for obj in ANform_form %} <table class="table" width="100%" border="0" cellspacing="0" cellpadding="0"> <thead class="thead-light"> <tr> <td width="11%" border="0" cellspacing="0" cellpadding="0"> <b> {% csrf_token %} {{ obj.Thema }} </b> </td> <td width="15%" border="0" cellspacing="0" cellpadding="0">Username</td> <td width="19%" border="0" cellspacing="0" cellpadding="0">Password</td> <td width="18%" border="0" cellspacing="0" cellpadding="0">E-Mail</td> <td width="37%" border="0" cellspacing="0" cellpadding="0">Anhang</td> <td> </td> <td></td> </tr> </thead> <tbody> <td></td> <td> {% csrf_token %} {{ obj.Username }} </td> <td> {% csrf_token %} {{ obj.Password }} </td> <td> … -
Django edits rows instead of adding a new one
Is there any reason why code like this would edit the only row from a table instead of creating a new one? newStudent = Student(name=var.name, mark=var.mark, year=newyear) newStudent.save() Explanation: I am working on student records. This view is called when I'm updating a student's information. var.name is the student's name before the edit and var.mark is his mark before the edit. newyear is the year I'm adding this information for. This view is called every year (i.e. a student has a new name and mark every year). After these lines, I proceed to edit the student's current year information. The problem: This code edits the only row from the Student table in the database instead of adding a new one. -
Django run tasks (possibly) in the far future
Suppose I have a model Event. I want to send a notification (email, push, whatever) to all invited users once the event has elapsed. Something along the lines of: class Event(models.Model): start = models.DateTimeField(...) end = models.DateTimeField(...) invited = models.ManyToManyField(model=User) def onEventElapsed(self): for user in self.invited: my_notification_backend.sendMessage(target=user, message="Event has elapsed") Now, of course, the crucial part is to invoke onEventElapsed whenever timezone.now() >= event.end. Keep in mind, end could be months away from the current date. I have thought about two basic ways of doing this: Use a periodic cron job (say, every five minutes or so) which checks if any events have elapsed within the last five minutes and executes my method. Use celery and schedule onEventElapsed using the eta parameter to be run in the future (within the models save method). Considering option 1, a potential solution could be django-celery-beat. However, it seems a bit odd to run a task at a fixed interval for sending notifications. In addition I came up with a (potential) issue that would (probably) result in a not-so elegant solution: Check every five minutes for events that have elapsed in the previous five minutes? seems shaky, maybe some events are missed (or others … -
Django how to compute the Percentage using annotate?
I want to compute the total average per grading categories and multiply it by given number using annotate this is my views.py from django.db.models import F gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(grading_Period = period).filter(Subjects = subject).filter\ (Grading_Categories__in = cate.values_list('id')).values('Grading_Categories').annotate( average_grade = Avg * F('Grading_Categories__PercentageWeight') / 100) this is my models.py class gradingCategories(models.Model): CategoryName = models.CharField(max_length=500, null=True) PercentageWeight = models.FloatField() class studentsEnrolledSubjectsGrade(models.Model): GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True, blank=True) _dates = models.CharField(max_length=255,null=True, blank=True) Grade = models.FloatField(null=True, blank=True) -
Web development using python
Just asking that what are the other libraries that should be known by a person for the full web development with the help of python currently i know pandas,numpy ,matlab ,matplot lib,django -
APScheduler Quits at Network Call
Im using a BlockingScheduler, and my function is invoked at the intended interval, but the whole function doesn't run, only the first line does. @register_job('interval', minutes=1) def run_content_cron(): send_sms('+5555555555', 'inside clock.py content') # this runs <database call> # function quits here--this never runs -
How to fix TypeError: 'module' object is not callable in python using BytesIO
I face the problem of TypeError: 'module' object is not callable. My aim is to use BytesIO to print in pdf. The code that seems to have the error is : def render_to_pdf(template_src, context_dict): template = get_template(template_src) context = context_dict html = template.render(context) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), dest=result, encoding="utf-8", ) And my Traceback indicating the error is : Traceback: File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/vhosts/intranet.rodkok.gr/apografi_new/intranet/views.py" in pdf_clients_analysis 1766. 'clients':clients File "/var/www/vhosts/intranet.rodkok.gr/apografi_new/intranet/views.py" in render_to_pdf 2176. result = BytesIO() Exception Type: TypeError at /pdf_analysis/2020-01-012020-02-27/ Exception Value: 'module' object is not callable It seems that the problem does not have to do with the type of the content(String or Byte) Any idea how to fix it? -
Reset Password Form Page not found
I have built a custom password reset from in Django, However after putting the information in password reset form I get a 4040 page not found error This is my view for reset_password def reset_password(request,username): if request.method == 'POST': form = PasswordResetForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) #added this to redirect user to custom url username = request.user.username return redirect(reverse('main:home', kwargs={'username': username})) #return redirect(reverse('main:home')) else: return redirect(reverse('main:reset_password')) else: form = PasswordResetForm(user=request.user) args = {'form': form} return render(request, 'reset_password.html', args) My urls at myapp/urls.py urlpatterns=[ path('signup/',views.signup,name='signup'), path('login',views.user_login,name='user_login'), path('',views.main_page,name='main_page'), path('<str:username>', views.home, name='home'), #replace home/edit with below path('<str:username>/edit', views.edit_profile, name='edit_profile'), path('<str:username>/password-reset', views.reset_password, name='reset_password'), ] and my form for password reset: class PasswordResetForm(PasswordChangeForm): class Meta: model = Profile fields = ('old_password','new_password1','new_password2') What seems to be the problem here? I do not know why I am getting this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/main/test3-b/login.html?next=/main/test3-b/password-reset This is my AbstractUser model in models.py (I do not have any other code in my models.py class Profile(AbstractUser): bio = models.TextField() university = models.CharField(max_length=30) def __str__(self): return self.username -
Images not appearing in saleor base.html
I am using divio to run my saleor server. I added files to my static assets image folder. When I add the image to my base html it doesn't appear. I have placed the images inside the /saleor/static/images folder and then ran the command docker-compose run --rm web npm run build-assets --production. However, my images still aren't appearing, what am I missing? -
Select intersected geometries between two tables in GeoDjango
I have two models A and B. Help please with the help of ORM to query A records that intersects with B records with geometry field: Model A: class ModelA(models.Model): id = models.IntegerField(primary_key=True) properties = JSONField() geometry = models.MultiPolygonField() Model B: class ModelB(models.Model): id = models.IntegerField(primary_key=True) properties = JSONField() geometry = models.GeometryField() // can be any valid geometry: Point, Polygon, MultiPolygon -
How do i solve HTTP Error 429: Too Many Requests?
Iam new to python and making a simple django app to download videos from youtube.It runs withou any error on local host but on production it throws an error : HTTP Error 429: Too Many Requests I know its sending too many request in short time but ho do i limit the request? -
Django 2.2 How to disable checkboxes in list view
Django 2.2 I have a list view controlled by admin.py class. No custom template, all default. I can control what fields from the table should be shown in the view with this: fields = ('myfield1','myfield2', ...). Each row in the list table has a checkbox in the first column: <td class="action-checkbox"> <input type="checkbox" name="_selected_action" value="123" class="action-select"> </td> My questions are: 1. How to disable those checkboxes ? 2. Can it be done for SOME of the checkboxes (let's say I have a list of pk ids for the rows I don't want to see checkboxes.) -
AttributeError: type object 'Product' has no attribute '_parler_meta' - DJANGO
When attempting to migrate my database in Django. I receive the following: Running migrations: Applying shop.0002_transactions...Traceback (most recent call last): File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/parler/models.py", line 942, in contribute_translations base = shared_model._parler_meta AttributeError: type object 'Product' has no attribute '_parler_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/migration.py", line 114, in apply operation.state_forwards(self.app_label, project_state) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/operations/models.py", line 86, in state_forwards list(self.managers), File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 96, in add_model self.reload_model(app_label, model_name) File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 157, in reload_model self._reload(related_models) File … -
Default image being displayed even after uploading another picture in Django
I'm working on a website where users can post advertisements on houses they want to put up on rent. So I have an image field in models.py, but no matter which picture I upload, the system keeps displaying the default photo. I have set up the media root and url as per the documentation in my settings.py and also added it to my urls. models.py: class advertisements(models.Model): place=models.CharField(max_length=30) address=models.CharField(max_length=50) bedroom=models.PositiveSmallIntegerField() rent=models.PositiveIntegerField() size=models.PositiveIntegerField() date_posted=models.DateTimeField(default=timezone.now) owner= models.ForeignKey(User,on_delete=models.CASCADE) image = models.ImageField(default='defaulthouse.jpg',upload_to='house_pics') def get_absolute_url(self): return reverse('advertisement_details', kwargs={'pk':self.pk}) def save(self, *args, **kwargs): super().save(*args, **kwargs) image=Image.open(self.image.path) views.py: class AdvertisementCreateView(LoginRequiredMixin, CreateView): model= advertisements fields=['image', 'place','address','bedroom','bathroom','rent','size'] def form_valid(self, form): form.instance.owner=self.request.user return super().form_valid(form) urls.py: urlpatterns = [ path('', AdvertisementListView.as_view(), name='HomePage'), path('advertisements/<int:pk>/',AdvertisementDetailsView.as_view() , name='advertisement_details'), path('create_advertisements',AdvertisementCreateView.as_view(), name='create_advertisements'), path('your_advertisements',views.your_advertisements, name='your_advertisements'), path('advertisements/<int:pk>/update',AdvertisementUpdateView.as_view() , name='advertisement_update'), path('advertisements/<int:pk>/delete',AdvertisementDeleteView.as_view() , name='advertisement_delete'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html: <div class="container"> <legend class="border-bottom mb-4 text-center"><h3>House Information</h3></legend> <h5 class="card-title">Location: {{object.place}} </h5> <img src="{{ object.image.url }}" alt="..." class="img-thumbnail"> <p> Full Address: {{object.address}}</p> <p>Number of bedrooms: {{object.bedroom}}</p> <p>Number of Bathrooms: {{object.bathroom}}</p> <p>House/Apartment Size: {{object.size}} squarefeet</p> <p>Rent per month: {{object.rent}} taka</p> <legend class="border-bottom mb-4 text-center"><h3>Owner Information</h3></legend> <p>Owner Name: {{object.owner}}</p> <p>Advertisement Posted on: {{object.date_posted}}</p> {% if object.owner == user %} <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'advertisement_update' object.id%}">Update</a> <a class="btn … -
Error "the Content-MD5 HTTP header you passed for your feed did not match the Content-MD5 we calculated for your feed"
I am trying to set a maximum price for a product using Amazon API in a Django (Python) environment. I already solved the problem with calculating the md5 function which value is exactly the same as Amazon MWS Scratchpad calculates. After solving this issue, I get now a "the Content-MD5 HTTP header you passed for your feed did not match the Content-MD5 we calculated for your feed" error message. My code is as follows: feedTxt = '<?xml version="1.0" encoding="utf-8"?><AmazonEnvelope xsi:noNamespaceSchemaLocation="amzn-envelope.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Header><DocumentVersion>1.01</DocumentVersion><MerchantIdentifier>MERCH_ID</MerchantIdentifier></Header><MessageType>Price</MessageType><Message><MessageID>1</MessageID><Price><SKU>J1-1UKW-8Z03</SKU><MaximumSellerAllowedPrice currency="EUR">999</MaximumSellerAllowedPrice></Price></Message></AmazonEnvelope>' feed = open('myXml.xml', mode='w+', buffering=-1, encoding='utf-8') feed.write(feedTxt) feed.close() encodedFeed = feedTxt.strip().encode('utf-8') md5 = hashlib.md5(encodedFeed).digest() encodedMd5 = base64.b64encode(md5) parsedMd5 = urllib.parse.quote(encodedMd5, safe='') request_string = construct_strings(seller, '', 'SubmitFeed', '2009-01-01', args_dict) # this function defines the string to be signed and is working 100%, since I use it for all the other requests I do feed = open('myXml.xml', mode='r', buffering=-1, encoding='utf-8') myFile = {'file': feed} response = requests.post(request_string, headers = {'Content-MD5': encodedMd5, 'Content-Type': 'text/xml'}, files = myFile) feed.close() It's my first question asked here in stackOverflow. I appreciate any hints you can give me. Thanks! -
Django dropdown is not populated
I want my dropdown to get populated with values from one of my db tables in my Django project, yet it remains blank and I can't figure out why. This is my html code of my home.html page: <select name="regions" id="regions"> {% for item in regions_list %} <option val="{{ item.name_reg }}"> {{ item.name_reg }} </option> {% endfor %} </select> models.py: class data_reg(models.Model): id = models.AutoField(primary_key=True) name_reg = models.TextField(db_column='NAME_REG', blank=True, null=True) class Meta: managed = True db_table = 'reg' views.py: def MyView(request): regions_list = RegionChoiceField() query_results_dict = { 'regions_list': regions_list, } return render(request,'home.html', query_results_dict) forms.py: class RegionChoiceField(forms.Form): regions = forms.ModelChoiceField( queryset=data_immo.objects.values_list("name_reg", flat=True).distinct(), empty_label=None ) -
fitting a data file with multiple sample rows into single Django model object instance
I'll do my best to summarize, I'm working with cycling data from the Fit File format, which samples every second with power, heartrate, cadence. I'm currently getting the data into a dataframe and it's formatted like this and repeated over several thousand rows for however long I rode in seconds. {'watts': 176, 'heartrate': 59, 'timestamp': datetime.datetime(2020, 2, 26, 16, 19, 25), 'cadence': 80, 'time': 0.0}, {'watts': 176, 'heartrate': 59, 'timestamp': datetime.datetime(2020, 2, 26, 16, 19, 26), 'cadence': 80, 'time': 1.0} I can upload the file into my database model but the catch is that each second becomes its own object, when really each ride should be the object. I'm having a heck of a time trying to think through this, I've tried doing ArrayField and JSONField in the model, but get the following error, which I imagine is related to how the dataframe is put together: (psycopg2.errors.DatatypeMismatch) column "watts" is of type integer[] but expression is of type integer LINE 1: ...tts, heartrate, timestamp, cadence, time) VALUES (176, 59, '... ^ HINT: You will need to rewrite or cast the expression. Just curious for advice on how to construct the model and/or the dataframe to get the object appearing how … -
Django user record not found
I am trying to extend the user model in django by using a Client model (this might not be the ideal way, but that boat has sailed). When I try to access a user record in a template I get the error: No Client matches the given query models.py class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) views.py def update_client_details(request): if request.user.is_authenticated: user = request.user # print('pk', user.pk) client = get_object_or_404(Client, pk=user.pk) If I print the user.pk I see what I expect. Why doesn't it return an object? -
Using `select_related` with a table with composite primary key [Django]
Is there a way for Django to support composite primary key in combination of select_related or prefetch_related? I have a Records table with a composite primary key (device_id, created) with a schema like this (simplified): class Records(models.Model): class Meta: managed = False unique_together = (("device", "created"),) # The primary key is really (device_id, created) device = models.ForeignKey("hardware.Device", primary_key=True, on_delete=models.CASCADE) created = models.DateTimeField(db_index=True) value = models.FloatField(default=0) A record belongs to a Device, which is modeled like this (simplified): class Device(models.Model): car = models.ForeignKey("cars.Car", on_delete=models.CASCADE) last_record_at = models.DateTimeField(null=True, blank=True) I wish to run a query that will return a list of devices, but for each one also contain the last record. In theory, this would be something like that: Device.objects.filter(...).select_related("car", "last_record") But obviously "last_record" is not a foreign key, since Records contains a composite primary key which Django doesn't support. What would be the best way to do this, other than rewriting the query in raw sql? Is there a reasonable way to override select_related to handle composite keys? -
Django / React Cross-Origin Request Blocked Error hosted Google App Engine django-cors-headers not working
The application backend (django) and frontend (react) are hosted on google cloud at the same app. I've installed django-cors-headers and referred to it in settings.py: INSTALLED_APPS = ( ... 'corsheaders', ... ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_REGEX_WHITELIST = ( 'http://localhost:3000', 'https?\://myapp\.appspot\.com\/?', 'https?\://frontend-dot-myapp\.appspot\.com\/?', ) As far as I understood CORS_ORIGIN_ALLOW_ALL should already resolve this problem, but it doesn't, I just got a bit desparate there trying things out. CORS_ORIGIN_WHITELIST didn't work as well for me that's why CORS_ORIGIN_REGEX_WHITELIST. I haven't changed anything in this setup but now the Cross-Origin error appears. Since the last code change I installed django-silk to profile the app. Removing it doesn't appear to resolve the issue, so I'm not sure whether it's related. Help greatly appreciated! in requirements.txt: django-cors-headers==3.2.1 -
TypeError at /update_order/27 __str__ returned non-string (type NoneType)
Type Error when i am clicking on Update Update Button Image Models -
How to Add Clickable Table Of Contents to ReportLab with Python
I have spent the last few hours battling with this issue with ReportLab in Python I would like to add a Clickable TOC with Page numbering. Here is a visual of what I did so far: I just added them as basic text. I tried to create a class MyDocTemplate to hold the Table Of contents. class MyDocTemplate(BaseDocTemplate): def __init__(self, filename, **kw): self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) template = PageTemplate('normal', [Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')]) self.addPageTemplates(template) def afterFlowable(self, flowable): "Registers the Table Of Contents entries" if flowable.__class__.__name__ == 'Paragraph': text = flowable.getPlainText() style = flowable.style.name if style == 'Heading1': self.notify('TOCEntry', (0, text, self.page)) if style == 'Heading2': self.notify('TOCEntry', (1, text, self.page)) def addPageNumber(canvas, doc): """ Add the page number """ text = "FOOTER HERE" page_num = canvas.getPageNumber() text1 = "Seite %s" % page_num text2 = todaydate text3 = "COURTAGEMODELL POOL" text4 = "COURTAGELISTE" canvas.drawRightString(260*mm, 3*mm, text1) canvas.drawRightString(220*mm, 3*mm, text2) pdf_name = FileName1 + con + str(number1) + con + str(number2) + ext2 pdf_name2 = "Complete" + con + str(number1) + con + str(number2) + ext2 #--------------------------------------------------------------- heading1_style = ParagraphStyle(name = 'Heading1', fontSize = 16, leading = 16) heading2_style = ParagraphStyle(name = 'Heading2', fontSize = 12, leading = 14,) # … -
M2M relations not deleted after clear()
If a user is de-activated I want all memberships deleted. I thought this code in models.py would do it. But is doesn't, the relation is still there. class User(AbstractUser): membership_type = ManyToManyField(MembershipType, blank=True) .... def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.old_is_active = self.is_active def save(self, **kwargs): # Membership is cancelled if self.old_is_active is True and self.is_active is False: self.membership_type.clear() super(User, self).save() -
Problems with fixing navbar to top of page
For some reason when running the following code my navbar seems to be stuck in the middle of my screen. Based on other nav's i've made before it should be fixed to the top so i'm super confused. any help is appreciated! <body> <div class="container-fluid"> <nav class="navbar sticky-top navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <div class="navbar-nav align-items-center"> <a class="navbar-brand bigbrand" href="{% url 'post_list' %}">My Tech blog</a> <a class="nav-item nav-link" href="{% url 'about' %}">About</a> <a class="nav-item nav-link" href="https://www.github.com">Github</a> <a class="nav-item nav-link" href="https://www.linkedin.com">LinkedIn</a> </div> <div class="navbar-nav ml-auto"> {% if user.is_authenticated %} <a class="nav-item nav-link" href="{% url 'post_new' %}">New Post</a> <a class="nav-item nav-link" href="{% url 'post_draft_list' %}">Drafts</a> <a class="nav-item nav-link" href="{% url 'logout' %}">Log out</a> <a >Welcome: {{ user.username }}</a> {% else %} <a class="nav-item nav-link" href="{% url 'login' %}" aria-label="Login"> <span class="fa fa-user" aria-hidden="true"></span></a> {% endif %} </div> </div> </nav> </div> {# The actual blog posts#} <div class="content container-fluid"> <div class="col-md-8"> <div class="blog_posts"> {% block content %} {% endblock %} </div> </div> </div> {# SCRIPTS#} <script type="text/javascript" src="{% static 'js/blog.js' %}"></script> </body> </html> image of my output: -
Django-React-Framework localhost api endpoints on Safari not working
this is a wild shot because I cannot figure out why it doesn't work right. I have a Django-react-framework (DRF) and a React project running. Both of them work. However, when I make any request to the Python project I do so with Postman, just because it is more convenient to have any parameter defined in there. When doing so all requests work. The problem I face currently is is that any request I make from Safari doesn't work. Any request to my Backend from Safari just gives me this console error. Failed to load resource: A server with the specified hostname could not be found. 0.chunk.js:609 When I try the same with Chrome however it works all fine. That's why I don't think that it is because of my Backend. I added the settings.py anyways. Additionally, React on Safari works when I use the api-endpoints that are already hosted on the server. Further Information: when running on the server DRF server the api-endpoints with api., the app page with app. and the landing page on the root url. On localhost it only server the app on root this time, and the api-endpoints stay on api. """ Django settings for …