Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework: load model data into serializer maually (to then send it as an HTTP payload / webhook)
So we have a post-save signal that calls a celery task that is using requests to notify one of our partners about an order by a user he has referred to us. I would like the payload to equal the detail view output of the order. So far so good. However, for test-ability purposes and also to avoid unnecessary HTTP calls, I would like to retrieve the instance from the DB (in the celery task), feed it to the serializer (OrderDetailSerializer) and then call requesst.post with serializer.data What is the easiest way to achieve that The closest question to this one I found is this Using Django rest framework as a rest client The answer suggested to use simple JSON serialization. However, it is not a good solution for us because the serializer hides some sensitive data and ads some nested data via NestedSerializers. -
python django logging: One single logger with more than one logging level
tl;dr: Is there any way to have one single logger that manages all loglevels? I am using the logging library on a certain django project. Django manages logging exactly the same as the regular logging library, but with the benefit that you can declare loggers, handlers, filters, etc. on a separate settings.py file. Currently, I have some loggers and handlers on my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers' : False, 'loggers': { 'info': { 'handlers' : ['std_err', 'info_logfile'], 'level': 'INFO', }, 'info.contract': { 'handlers': ['contract_info_logfile'], 'level': 'INFO', 'propagate': True, } }, 'handlers': { 'std_err': { 'class': 'logging.StreamHandler' }, 'info_logfile': { 'class': 'logging.FileHandler', 'filename': 'info.log', 'formatter': 'default', }, 'contract_info_logfile': { 'class': 'logging.FileHandler', 'filename': 'contract.info.log', 'formatter': 'default', } } 'formatters': { 'default': { 'format': '%(asctime)s [%(module)s] %(message)s', } } } In my code, I simply run: logger = logging.getLogger('info.contract') logger.info("Some info message...") Which prints 2021-01-24 03:05:02,063 [contract_generator] Some info message... to console. This works very well and is what I expect. The problem I am having is the following: In order to log to different files depending on the loglevel, I would have to create a new logger for each loglevel. Which is to say, the following doesn't work: logger = … -
Using Django, SimpleJWT checking User permission to show content belongs to his own company
I am using React(front), Django(server-side), Simple JWT for User Auth Model and Postgres DB. Let me explain my model: Company owns many properties, and each company has multiple users. As a user logs in, I want them to see a list of properties that belongs to their own company. As the user selects any property from the list, I need to again check if the user has permission and then run the queries. I am currently using Simple JWT for authentication. As the user logs in, the backend generates Access and Refresh tokens. With every request sent from the user side, I am sending JWT access token. On the server side, I want to decode the token, look at what company user belongs to, filter queries accordingly and send the JsonResponse. Here is my Company Model: class Company(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='company_user', on_delete=models.CASCADE, null=True) company_name = models.CharField(max_length=200, null=True) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ['name'] def __str__(self): return self.name Here is the property model: class Property(models.Model): company = models.ForeignKey(Company, related_name='prop_company', null = True, on_delete=models.CASCADE) property_name = models.CharField(max_length=200, null=True) property_type = models.CharField(max_length=200, null=True) def __str__(self): return self.property_name Here is the property data class PropertyData(models.Model): data = models.ForeignKey(Property, related_name='property_data', null … -
Updating database on Django
Good day SO. I want to ask something basic. I tried on my end to update my data from html to save to database but to no avail. My Model structure is Account extends to AbstractBaseUser, BaseUserManager and CompanyAccount links to Account by OneToOneField. I can say that my Model should have no problem since I can Register Account and Company Account without any problems. views.py @login_required(login_url='/login/') def user_my_page(request, *args, **kwargs): context = {} context['form_type'] = 'update' context['account_type'] = request.user.account_type if request.POST: if request.user.account_type == 1: company = CompanyAccount.objects.get(account=request.user) account_form = CompanyAccountForm(request.POST, instance=request.user) if account_form.is_valid(): account_form.save() print(request.POST) print('SAVE') else: print('ERROR') forms.py class AccountCreationForm(UserCreationForm): accuser_id = forms.CharField(max_length=10, help_text="Required") class Meta: model = Account fields = ("accuser_id", "password1", "password2") class CompanyAccountForm(forms.ModelForm): class Meta: model = CompanyAccount fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['company_name'].widget.attrs.update({'class': 'content-input'}) self.fields['company_name_kana'].widget.attrs.update({'class': 'content-input'}) print(request.POST) <QueryDict: {'csrfmiddlewaretoken': ['6zrwt68PNiJKrgZcKanDcVJkqAtogbQbNk2wHwjOzg7ybfq3Lyei9ZqdbmAJcYrV'], 'company_name': ['TESTING'], ....etc This part here, it does print SAVE on my terminal but it does not save to the database. -
django is m2m relationship really necessary?
So I have two models like this. class Channel(BaseModel): class Meta: verbose_name = 'channel' verbose_name_plural = 'channels' indexes = [ models.Index(fields=['box', 'name'], name='channel_box_name_idx'), ] def __str__(self): return self.name def get_next_position(self): aggregate = self.box.channels.aggregate(models.Max('position')) return (aggregate['position__max'] or -1) + 1 def save(self, *args, **kwargs): if self._state.adding: # we insert the object's position if # it hasn't been created yet. We need to do # this explicitly because django doesn't # allow more than one auto-field self.position = self.get_next_position() super(Channel, self).save(*args, **kwargs) return self.box.channels.add(self) super(Channel, self).save(*args, **kwargs) objects = models.Manager() name = models.CharField(max_length=100, validators=[MinLengthValidator(2)]) box = models.ForeignKey('api_backend.Box', on_delete=models.CASCADE) position = models.PositiveSmallIntegerField(db_index=True) REQUIRED_FIELDS = [name, box] class Box(BaseModel): class Meta: verbose_name = 'box' verbose_name_plural = 'boxes' indexes = [ models.Index(fields=['owner'], name='box_owner_idx'), models.Index(fields=['owner', 'name'], name='box_name_owner_idx'), ] def __str__(self): return self.name objects = models.Manager() icon = models.ImageField(upload_to='icons/', storage=DefaultStorage) name = models.CharField(max_length=100, validators=[MinLengthValidator(2)]) owner = models.ForeignKey('api_backend.User', on_delete=models.CASCADE) channels = models.ManyToManyField('api_backend.Channel', related_name='box_channels') REQUIRED_FIELDS = [name, owner] Channel has an attribute box. And box has a m2m field channels. so in this type of relationship, whenever I create the channel with the box, I need to add the same to the box's m2m field channels. Is something like this really necessary? Like I need to have an extra … -
How do I add what I have written in my forms.py into views.py
Hi I have written a function in my forms.py to check to make sure that if a the form submitted has a slug or title that is the same as a blog post created before, they will return a message saying that the title already exists. How do I include this in my views.py so that it will work in the template? or did I write my function in forms.py wrongly? because the form isnt valid now. Note: There is no slug field in my form. The slug is only for the url..thank you! views.py def create_blog_view(request): context = {} form = CreateBlogPostForm(request.POST or None, request.FILES or None) if form.is_valid(): obj= form.save(commit = False) author = Account.objects.filter(email=user.email).first() obj.author = author obj.save() obj.members.add(request.user) return redirect('HomeFeed:main') context['form'] = form return render(request, "HomeFeed/create_blog.html", {}) forms.py class CreateBlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['chief_title', 'brief_description'] BlogPost.objects.exclude(pk=self.instance.pk).filter(chief_title__iexact=chief_title): def clean_slug(self): slug = slugify(self.cleaned_data.get("chief_title")) if len(self.cleaned_data.get("slug", )) == 0 \ else self.cleaned_data.get("slug", ) if BlogPost.objects.filter(slug=slug).exists(): self.add_error("slug", "BlogPost with the same title/slug already exists") return slug html <label for="id_title">Chief Title!</label> <input class="form-control" type="text" name="chief_title" id="id_title" placeholder="Title" required autofocus> </div> {{form.chief_title.errors}} -
How to send url as slug field into url in Django
I have my urls.py as this: from django.urls import path from . import views urlpatterns = [ path('link',views.get_text,name='text'), path('link/<link>',views.show,name='show') ] When I enter a url like http://127.0.0.1:8000/link/https://www.geeksforgeeks.org/gate-cs-notes-gq/, it is showing page not found as it is checking the / in the slug url. I am storing the url and other fields in database, so I want to retrieve the database objects using the url. How to do such that when I enter a url in the browser, it takes the entire url as link field in urls.py , so that I can retrieve the db objects from views.py in this way: def show(request,link): objs = Links.objects.filter(link=link).values() return HttpResponse('link') -
Wagtail adding childpage directory before static paths in base.html
I have a project set up with the following models.py file: """Flexible page.""" from django.db import models from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.models import Page from wagtail.core.fields import RichTextField class FlexPage(Page): """Flexibile page class.""" template = "flex/flex_page.html" # @todo add streamfields # content = StreamField() subtitle = models.CharField(max_length=100, null=True, blank=True) Flexbody = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel("subtitle"), FieldPanel('Flexbody', classname="full"), ] class Meta: # noqa verbose_name = "Flex Page" verbose_name_plural = "Flex Pages" I also have a "base.html" that has static paths like: <link rel="stylesheet" id="main-css" href="./static/SiteFiles/main.css" type="text/css" media="all"> <link rel="stylesheet" id="tether-css" href="./static/SiteFiles/Sitetether.css" type="text/css" media="all"> <link rel="stylesheet" id="bootstrap-css" href="./static/SiteFiles/bootstrap.min.css" type="text/css" media="all"> <link rel="stylesheet" id="font-awesome-css" href="./static/SiteFiles/font-awesome.css" type="text/css" media="all"> On the homepage, I'm able to get everything to load properly, but when I create a flexpage, I get the following error: [23/Jan/2021 21:07:44] "GET /getting-started/static/SiteFiles/Sitetether.css HTTP/1.1" 404 3333 Not Found: /getting-started/.static/SiteFiles/wp-emoji-release.min.js.download It seems like when I try to extend the "base.html" file, within the child pages, that it is adding a directory to my paths. I'm not sure how to override this behavior. -
how to generally reference a django url that has parameter
It's my urls.py app_name = "medicalrecord" urlpatterns = [ path("filesharing/<str:username>/", views.FileSharingView, name="FileSharingView"), ] in my css.html ... {% url 'medicalrecord:FileSharingView' "IDK" as medicalrecord_file_sharing %} ... {% if request.path == medicalrecord_file_sharing %} <link rel="stylesheet" type="text/css" href="{% static 'medicalrecord/css/filesharing.css' %}"> {% endif %} IDK what to put there, any username i put it only matches that one, how to set it dynamic ? -
How to populate auth.groups and auth.group_permissions tables with initial data in Django project
Context I am using PostgreSQL. I would like to immediately populate the auth.groups and auth.group_permissions tables, after the very first migration of my project. So, after I have set up these tables the way I want them, I dump them by running python manage.py dumpdata auth.groups auth.group_permissions > core/fixtures/initial_data.json The resulting file is this [ { "model": "auth.group", "pk": 1, "fields": { "name": "Admin", "permissions": [ 29, 31, 32, 33, 34, 35, 36 ] } }, { "model": "auth.group", "pk": 2, "fields": { "name": "Operators", "permissions": [ 42, 43, 44, 39, 40 ] } }, { "model": "auth.group_permissions", "pk": 12, "fields": { "group": 1, "permission": 32 } }, { "model": "auth.group_permissions", "pk": 13, "fields": { "group": 1, "permission": 33 } }, { "model": "auth.group_permissions", "pk": 14, "fields": { "group": 1, "permission": 34 } }, { "model": "auth.group_permissions", "pk": 15, "fields": { "group": 1, "permission": 35 } }, { "model": "auth.group_permissions", "pk": 16, "fields": { "group": 1, "permission": 36 } }, { "model": "auth.group_permissions", "pk": 17, "fields": { "group": 1, "permission": 29 } }, { "model": "auth.group_permissions", "pk": 18, "fields": { "group": 1, "permission": 31 } }, { "model": "auth.group_permissions", "pk": 19, "fields": { "group": 2, "permission": 39 } }, { … -
My bootstrap modal is not showing up after it said the process was successful
this html code for my modal - the page displays fine but when click the button to show the modal it doesn't show up but when i inspect my web page it says my says the process was successful but i cant see it and i also got errors- i am still new with JavaScript and html <td><a href="#" class ="btn btn-success show_notification" data-toggle="modal" data-target="#myModal">Send Notifications</a></td> </tr> {% endfor %} </tbody> </table> </div> <!-- /.card-body --> </div> <!-- /.card --> </div> </div> </div> </section> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Send Notification <span id="name"></span></h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <div class="form-group"> <input type="text" name="message" class="form-control" id="message"> <input type="hidden" name="admin_id" class="form-control" id="admin_id"> </div> </div> <div class="form-group"> <button class="btn btn-info btn-block" type="button"> Send Notification</button> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> {% endblock main_content %} {% block custom_js %} <script> $(".show_notification").click(function(){ var admin_id=$(this).parents("tr").children("td:eq(0)").text(); var admin_name=$(this).parents("tr").children("td:eq(3)").text(); console.log(admin_id); $("#admin_id").val(admin_id); $("#name_span").text(admin_name); }); </script> {% endblock custom_js %} this is the errors that came up in my web console > admin_send_notification_admin:410 GET > http://127.0.0.1:8000/static/plugins/bootstrap/js/bootstrap.bundle.min.js > net::ERR_ABORTED 404 (Not Found) jquery.vmap.min.js:10 Error: <svg> > attribute width: Expected length, "undefined". VectorCanvas.setSize … -
Runtime model generation in Django or other languages
I'm asking this question for hearing about advice and having an idea about the possibility of this type work. Not asking for any code help, just advice, and a little leading would be helpful, if it is still the wrong place to ask this question, sorry about that. I would like to build an application that lets users upload a CSV or excel file and generate a SQL table at the backend at that time and store data into the table. Then print the loaded data in UI. I did it before in a terrible and messy way by using the Create Table query and select query for printing data. I believe you will think of me how a programmer can be so ridiculous if you see these codes. That's the reason I want to learn if there is a better and standard way to do the same thing or shouldn't do something like that at all? And how other companies do this type of works? You can advise different programming languages if there are any. I read about documents Dynamic Models. I understand a little, but they don't advise to build in that way, so I don't know if … -
Linking two tables with ManyToManyField in Django
I have two db tables: Estados: estado_id, estado_nome Familia: familia_id, familia_nome One family can have multiple Estado, in my mysql db it uses a tertiary table, with composite keys, as we all know django don't supports it. I'm willing to do whatever it takes to make it work. Thank you very much for reading my question and i hope you have a good day. -
I can't install graphene-django in GitHub actions
I am building a Django project, and I am using GitHub actions to run python manage.py test whenever I push. The problem is that in the project, I am using the graphene-django package, which's available to install via pip install graphene-django. The problem is that, for some reason, this doesn't seem to work (it outputs an error). I have tried everything: pip install graphene-django pip install "graphene-django>=2.0" pip install --user graphene-django pip install --user "graphene-django>=2.0" pip3 install graphene-django pip3 install "graphene-django>=2.0" pip3 install --user graphene-django pip3 install --user "graphene-django>=2.0" Some of these commands display a different error, but the most common is this: Collecting promise>=2.1 (from graphene-django>=2.0) Downloading https://files.pythonhosted.org/packages/cf/9c/fb5d48abfe5d791cd496e4242ebcf87a4bb2e0c3dcd6e0ae68c11426a528/promise-2.3.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> ModuleNotFoundError: No module named 'setuptools' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-5vr1pems/promise/ Here is my YAML file for the Action (with the last intslling attempt): name: Testing on: push jobs: test_vote: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Run Django unit tests run: | pip3 install --user django pip3 install --user "graphene-django>=2.0" python3 manage.py test env: # Random key SECRET_KEY: '!nj1v)#-y)e21t^u@-6tk+%+#vyzn30dp+)xof4q*y8y&%=h9l' Any help would be really appreciated, … -
How to deal with an abandoned Django package ( that is not compatible anymore with new version of Django/python )?
In my case there is no update in Django-suit package, anyone know how to deal with it? -
having trouble configuring Django on the atom editor for a Mac computer
I am trying to set up Django the newest version with python 3 and I keep getting errors about the path way. this is what it is saying and the following is my configurations. Note: I have uninstalled and installed and even wrote it to the exact way their website directs with no luck. it just changes around the error. terminal: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/patrickjobe/Desktop/wordcount/wordcount/urls.py", line 20, in <module> path('index/', views.index), NameError: name 'path' is not defined urls.py page configs rom django.contrib import admin from . import views urlpatterns = [ path('index/', views.index), path('admin/', admin.site.urls), ] settings.py page TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':['templates'], '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', ], }, }, ] views.py page from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, 'index.html') -
How overwrite django-friendship
I am using a third party application called "django-friendship" and I want to adapt it to my project. To adapt it to my project I need to overwrite several functions and urls that come by default, but I don't know how to overwrite them. The source code is here: https://github.com/revsys/django-friendship For example, I want to overwrite the following function in views.py: def all_users(request, template_name="friendship/user_actions.html"): users = user_model.objects.all() return render( request, template_name, {get_friendship_context_object_list_name(): users} ) and for example I want this function to do nothing, just print a text on the screen (not its purpose but to make the example simpler) in this way: def all_users(request, template_name="friendship/user_actions.html"): print("Hello World") I have used the following import: from friendship.views import all_users But it does not work, it still uses the function of the third party application and not mine. On the other hand, "django-friendship" uses the following urls: friendship/ ^users/$ [name='friendship_view_users'] friendship/ ^friends/(?P[\w-]+)/$ [name='friendship_view_friends'] friendship/ ^friend/add/(?P<to_username>[\w-]+)/$ [name='friendship_add_friend'] friendship/ ^friend/accept/(?P<friendship_request_id>\d+)/$ [name='friendship_accept'] friendship/ ^friend/reject/(?P<friendship_request_id>\d+)/$ [name='friendship_reject'] friendship/ ^friend/cancel/(?P<friendship_request_id>\d+)/$ [name='friendship_cancel'] friendship/ ^friend/requests/$ [name='friendship_request_list'] friendship/ ^friend/requests/rejected/$ [name='friendship_requests_rejected'] friendship/ ^friend/request/(?P<friendship_request_id>\d+)/$ [name='friendship_requests_detail'] friendship/ ^followers/(?P[\w-]+)/$ [name='friendship_followers'] friendship/ ^following/(?P[\w-]+)/$ [name='friendship_following'] friendship/ ^follower/add/(?P<followee_username>[\w-]+)/$ [name='follower_add'] friendship/ ^follower/remove/(?P<followee_username>[\w-]+)/$ [name='follower_remove'] friendship/ ^blockers/(?P[\w-]+)/$ [name='friendship_blockers'] friendship/ ^blocking/(?P[\w-]+)/$ [name='friendship_blocking'] friendship/ ^block/add/(?P<blocked_username>[\w-]+)/$ [name='block_add'] friendship/ ^block/remove/(?P<blocked_username>[\w-]+)/$ [name='block_remove'] How can I modify … -
Is including the user field in two related models a bad practice? (Django)
I’m fairly new to Django and programming in general. I’m building a tool for a friend in the construction industry. Basically the client bids for a tender and if they win they sign a contract. A contract can have multiple projects and a project can have multiple jobs. But the user should also be able to create a job for smaller projects that are not under a contract. Every job must be under a project. If the user has a contract I want the user journey to be as the following: Create a contract -> create a project -> create a job. I want to link the contract to the user and the job to the user as well but I’m not sure if it’s a good practice to include the user field twice in two related models. I’d like to know if my solution is wrong and a bad practice, and if there’s a better solution. Thanks! class Contract(TimeStampedModel): owner = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) title = models.CharField( max_length=100, blank=False, unique=False) starting_date = models.DateTimeField(default=timezone.now, blank=True) class Meta: verbose_name_plural = "Contracts" def __str__(self): return self.title class Project(TimeStampedModel): name = models.CharField( max_length=50, blank=False, unique=False) contract = models.ForeignKey( Contract, on_delete=models.RESTRICT, blank=False, related_name='contract', … -
Reverse for 'update_prices' not found. 'update_prices' is not a valid view function or pattern name
i am building an amazon web scraper where you can submit a link and track the price of your product. When i try to go to this site this error pops up and it also says that the error is at line 0 at base.html How do i get rid of this error models.py from django.db import models from .utils import get_link_data # Create your models here. class Link(models.Model): name = models.CharField(max_length=220, blank=True) url = models.URLField() current_price = models.FloatField(blank=True) old_price = models.FloatField(default=0) price_difference = models.FloatField(default=0) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.name) class Meta: ordering = ('price_difference', '-created') def save(self, *args, **kwargs): name, price = get_link_data(self.url) old_price = self.current_price if self.current_price: if price != old_price: diff = price - old_price self.price_difference = round(diff, 2) self.old_price = old_price else: self.old_price = 0 self.price_difference = 0 self.name = name self.current_price = price super().save(*args, **kwargs)``` **views.py** ```from django.shortcuts import render, redirect from django.urls import reverse_lazy from .models import Link from .forms import AddLinkForm from django.views.generic import DeleteView def home_view(request): no_discounted = 0 error = None form = AddLinkForm(request.POST or None) if request.method == 'POST': try: if form.is_valid(): form.save() except AttributeError: error = "Ups ... couldn't get the name or the … -
Django static file not working properly in production
This is the first time to deploy a project for development. Here are the steps that I have made to ensure that the static files are correctly reflected on the site. Added STATIC_ROOT to the setting.py STATIC_ROOT = '/home/ahesham/Project/static/' STATIC_URL = '/static/' python manage.py collectstatic Here is the outcome: You have requested to collect static files at the destination location as specified in your settings: /home/User/Project/static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes 1545 static files copied to '/home/User/Project/static'. (venv) User@django-server:~/Project$ python manage.py runserver 0.0.0.0:8000 Now the problem is that when I opened the site, not all CSS files are not reflecting and in the console it is proving it: Failed to load resource: the server responded with a status of 404 (Not Found) login.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) style.min.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) meme.jpg:1 Failed to load resource: the server responded with a status of 404 (Not Found) loginutil.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) login.css:1 … -
Django postgres migration error foreign key constraint does not exist
I'm using a PostgreSQL database hosted with aws, everytime I try to migrate (python manage.py migrate) I run into this error: column "id" referenced in foreign key constraint does not exist. I have tried removing the two foreign keys that I'm using with no luck I still get the same error. I have also tried this solution with no luck. The rest migrates with no problem, Just this one error Model.py class Subprogram(models.Model): title = models.CharField(max_length=100) program = models.ForeignKey(Program, on_delete=models.CASCADE) budget = models.DecimalField(default=0, decimal_places=0, max_digits=11) class Project(models.Model): name = models.CharField(max_length=100) budget = models.DecimalField(decimal_places=0, max_digits=11) budget_year = models.PositiveIntegerField(default=current_year(), validators=[MinValueValidator(current_year)]) file = models.FileField(blank=True) subprogram = models.ForeignKey(Subprogram, on_delete=models.CASCADE, default=) -
ManyToManyField In HTML
Can someone please let me know the proper way to display values that have been entered in a ManyToMany data field? In my project, a contractor can have multiple trades or skills, this should be entered in the trade field. class SubTrade(models.Model): strade = models.CharField("Trade", max_length=255) def __str__(self): return self.strade def get_absolute_url(self): return reverse ("trade_full", kwargs={"pk": self.id}) class SubContractor(models.Model): nameF = models.CharField("First Name", max_length=255, blank = True, null = True) nameL = models.CharField("Last Name", max_length=255, blank = True, null = True) nameN = models.CharField("Nickname", max_length=255, blank = True, null = True) trade = models.ManyToManyField('SubTrade') phone = models.CharField("Phone", max_length=255, blank = True, null = True) email = models.EmailField("Email", max_length=254, blank = True, null = True) address = models.CharField("Address", max_length=255, blank = True, null = True) dateC = models.DateTimeField("Date Created", auto_now_add=True) dateU = models.DateTimeField("Last Updated", auto_now=True) note = models.TextField("Notes", blank = True, null = True) def __str__(self): return '%s %s' % (self.nameF, self.nameL) def get_absolute_url(self): return reverse ("contractor_full", kwargs={"pk": self.id}) These are my views. class SubContractorCreateView(CreateView): model = SubContractor template_name = "project/contractoradd.html" fields = ['nameF', 'nameL', 'nameN', 'trade', 'address', 'phone', 'email', 'note'] def form_valid(self, form): return super().form_valid(form) This is my HTML Code {% for contractor in contractor %} Last Name: {{contractor.nameL}} <br> … -
How to get an evironment variable value in YAML file?
I am working on a Django project, and I am using GitHub for source control purposes. I am using GitHub actions to run python3 manage.py test when pushing. I don't want to post my secret key to the repository. So I stored it on an environment variable and used os.environ.get('SECRET_KEY') to keep it secret. The problem is that by doing this, GitHub doesn't know what the SECRET_KEY is. There is a way to set custom environment variables in the YAML file in the workflow directory, but if I put the SECRET_KEY there, there is no point in covering it in settings.py. Does anybody know what I can do? -
AssertionError: `create()` did not return an object instance
I am getting the error below while sending a request to a UserRegisterView: File "/Users/MichaelAjanaku/Desktop/test/afrocode/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/MichaelAjanaku/Desktop/test/leave/views.py", line 22, in post serializer.save() File "/Users/MichaelAjanaku/Desktop/test/afrocode/lib/python3.6/site-packages/rest_framework/serializers.py", line 207, in save '`create()` did not return an object instance.' AssertionError: `create()` did not return an object instance. I don't know why such occurs. Here is my views.py: class UserRegistrationView(CreateAPIView): serializer_class = UserRegistrationSerializer permission_classes = (AllowAny,) def post(self, request): serializer = self.serializer_class(data= request.data) serializer.is_valid(raise_exception=True) serializer.save() status_code = status.HTTP_201_CREATED response = { 'success' : 'True', 'status code' : status_code, 'message' : 'User registered successfully' } and the serializers: class UserRegistrationSerializer(serializers.ModelSerializer): profile = UserSerializer(required=False) class Meta: model = User fields = ('email', 'password','profile' ) extra_kwargs = {'password': {'write_only' : True}} def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create_user(**validated_data) UserProfile.objects.create( user = user, first_name = profile_data['first_name'], last_name= profile_data['last_name'], ) Please what is causing the error? Thanks -
Add tag attribute and description to Django rest framework
Need help, there is serializers.py and it has the following class written in it: class menu(serializers.ModelSerializer): a = serializers.CharField(default='http://localhost/1') class Meta: model = Object fields = ['a'] At the output, I get this line: <a>http://localhost/1</a> How to write the 'menu' class correctly so that the following construction is output: <a href="http://localhost/1">Menu 1</a> Thank you!