Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2 get user `id` upon making request on forms.py
My forms.py that appears to contain the error in retriving the user id value upon submitting the form. from django.contrib.auth.models import User from Scanner.models import T class SubmitD(ModelForm): #model form fields here class Meta: model = T fields = ['field1','field2'] def save(self, request): instance = self.cleaned_data #other fields current_user = request.user d.FKtoClient_id = current_user.id d.save() It appears the following line is failing to gather a user id for the user logged in: current_user = request.user d.FKtoClient_id = current_user.id The associated views.py declaration: def APND(request): form = SD(request.POST) # A form bound to the POST data if request.method == 'POST': # If the form has been submitted... if form.is_valid(): # If form input passes initial validation... dnmcleaned = form.cleaned_data['domainNm'] ## clean data in dictionary form.save(request) #save cleaned data to the db from dictionary` try: return HttpResponseRedirect('/PU/?f=' + dnmcleaned) except: raise ValidationError(('Invalid request'), code='300') else: return HttpResponseRedirect('Failure/') else: form = SD() I verified there are (2) users in auth_user table. However, I keep getting this error: (1048, "Column 'FKtoUser_id' cannot be null") How can I resolve this? Thank you. -
How to format a number in django and respect localization
I wrote a custom filter like this which calls this method in a util file: def util_format_number(value): return "{:,.1f}".format(value) The idea is to only show one decimal place...but when used inside a template it won't give me a localized number like I have configured in settings: LANGUAGE_CODE = 'es-es' USE_I18N = True USE_L10N = True USE_THOUSAND_SEPARATOR = True DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3 The desired result would be 23.444.523,3 My actual filter looks like this: @register.filter def format_number(value): return util_format_number(value) I want to be able to use the formatter not only in templates, but inside view code where I create custom graphs (that I later print in the templates). Any hints? Best regards and thanks in advance. -
Delete object with form in django
I'm displaying a table. In every line there should be a delete button which deletes the element from the table. My problem is, I'm not sure how to pass the id of the element to the view. html: {% for post in posts %} <div> <h3>Zuletzt ausgewählt:</h3> <p>published: <b>{{ post.pub_date }}</b> </p> <p> name: <b>{{ post.Name }}</b> anmeldung: <b>{{ post.get_Anmeldung_display }}</b> essen: <b>{{ post.get_Essen_display }}</b> <form action="" method="POST"> {% csrf_token %} <input class="btn btn-default btn-danger" name="delete" type="submit" value="Löschen"/> </form> </p> <p> Email: <b>{{ post.Email }}</b> </p> </div> {% endfor %} views.py if request.method == 'POST' and 'delete' in request.POST: Eintrag.objects.filter(pk=id).delete() return HttpResponseRedirect(request.path) So I need to pass post.pub_date of every post to the view, how can I accomplish that? -
Django rest framework image upload error
This is my UserProfile model, class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE, ) badge = models.ImageField(upload_to='media/badges/', null=True) reputation = models.IntegerField(default=0) status = models.CharField(max_length=255, null=True, blank=True) thumbnail = models.ImageField(upload_to='media/user/', blank=True, null=True) And this is the Serializer class, class UserProfileSerializer(serializers.ModelSerializer): thumbnail = serializers.ImageField(max_length=None, use_url=True) class Meta: model = models.UserProfile fields = ('badge', 'reputation', 'status', 'thumbnail',) My API to update an image looks like this, class CreateUpdateUserThumbnail(views.APIView): def post(self, request, **kwargs): try: user = User.objects.get(id=kwargs.get('user_id')) except User.DoesNotExist: return Response({"Error": "User does not exist"}, status=status.HTTP_404_NOT_FOUND) request.data['user_id'] = user.id serializer = UserProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is the error that I get when I try to upload an image using POSTMAN. return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: bouncer_userprofile.user_id How do I associate a user_id with the serializer data? -
how to use cookiecutter-django scss
I used the recent cookiecutter django package to generate a new django product. But I am having trouble with the sass/scss compilation aspect. I looked at this, and its no help, as I need to setup the package.json to run any commands. I tried to make one, but I cannot seem to get it to run. { "name": "my_awesome_project", "version": "1.0.0", "description": "My Awesome Project ==================", "main": "index.js", "directories": { "doc": "docs" }, "scripts": { "scss": "sass --load-path my_awesome_project/static/sass/ my_awesome_project/static/css/a.css" }, "author": "", "license": "ISC", "dependencies": { "compass": "^0.1.1" } } In all honesty, I don't really know what Im doing with this part, nor where to start. -
How to config mysql with django and phpmyadmin
I am using django for my backend and mysql for database on nginx webserver on digitalocean. I want to use phpmyadmin to manipulate my database. Is there a way to do it? Thank you. -
Getting 200 ok status but giving response error
{ "errors": "Unable to log you in, please try again.", "success": false } code: @csrf_exempt def token_new(request): if request.method == 'POST': email = request.POST.get('username') print email try: UserObj = CognitoUser.objects.get(user__email=email) username = UserObj.user.username group = UserObj.user.groups.filter(name__in=['Admin','Manager']) group_name = '' if group: group_name = group[0].name except: return JsonResponseUnauthorized("Unable to log you in, please try again.") password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user: TOKEN_CHECK_ACTIVE_USER = getattr(settings, "TOKEN_CHECK_ACTIVE_USER", False) if TOKEN_CHECK_ACTIVE_USER and not user.is_active: return JsonResponseForbidden("User account is disabled.") token = token_generator.make_token(user) data = { 'token': token, 'user': user.pk, 'userName':UserObj.user.username, 'companyId':UserObj.company.companyid, 'companyApikey':UserObj.company.apikey, 'group_name':group_name } request.session['token'] = token request.session['token'] = user.pk return JsonResponse(data) else: return JsonResponseUnauthorized("Unable to log you in, please try again.") else: return JsonError("Must include 'username' and 'password' as POST parameters.") else: return JsonError("Must access via a POST request.") -
ValueError: Invalid literal for int () with base10: 'egypt'
models.py from django.core.validators import RegexValidator from django.db import models from django.db.models import Model # Create your models here. class Name(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class Action(models.Model): action_name = models.CharField(max_length=250) def __str__(self): return self.action_name class Status(models.Model): item_status = models.CharField(max_length=250) def __str__(self): return self.item_status class Size(models.Model): item_size = models.CharField(max_length=250) def __str__(self): return self.item_size class Color(models.Model): item_color = models.CharField(max_length=250) def __str__(self): return self.item_color class Town(models.Model): city = models.CharField(max_length=250) def __str__(self): return self.city class Item(models.Model): # custom validators alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') # fields dress_name = models.ForeignKey(Name, on_delete='DO_NOTHING', null=False, verbose_name='وصف الفستان',) dress_size = models.ForeignKey(Size, on_delete='DO_NOTHING', verbose_name='مقاس الفستان') dress_color = models.ForeignKey(Color, on_delete='DO_NOTHING', verbose_name='لون الفستان') dress_image1 = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, verbose_name='الصورة الأساسية للفستان', help_text='لا يمكنك تركها فارغة',) dress_image2 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, verbose_name='صورة إضافية ') dress_image3 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, verbose_name='صورة إضافة ') dress_action = models.ForeignKey(Action, on_delete='DO_NOTHING', verbose_name='الفستان معروض لل ', help_text='للبيع او للإيجار ') dress_price = models.IntegerField(default=1, verbose_name='السعر') dress_mobile = models.CharField(max_length=20, validators=[alphanumeric], verbose_name='رقم الهاتف ') created_by = models.CharField(max_length=250,) created_username = models.CharField(max_length=250, default='unknown') created_at = models.DateTimeField(auto_now=True) dress_active = models.BooleanField(default=False) dress_special = models.BooleanField(default=False) dress_town = models.ForeignKey(Town, on_delete='DO_NOTHING',default='القاهرة') class Ads(models.Model): title = models.CharField(max_length=50) text = models.CharField(max_length=50) image = models.ImageField(upload_to='documents/%Y/%m/%d', null=False,) created_at = models.DateTimeField(auto_now=True) That is my models.py file, whenever I try to do makemigrations … -
Django / makemigrations ModuleNotFoundError: No module named 'idmp_core.apps.IdmpCoreConfigdjango';
I'm learning Django... And there is an error I'm not able to fix when running makemigrations command. I got the error ModuleNotFoundError: No module named 'idmp_core.apps.IdmpCoreConfigdjango'; 'idmp_core.apps' is not a package. What is puzzling me is the django word appened at the end of idmp_core.apps.IdmpCoreConfig string that is part of INSTALLED_APPS = [ 'idmp_core.apps.IdmpCoreConfig' 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', My project tree structure is the following one: D:. | manage.py | +---idmp_core | | admin.py | | apps.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | | __init__.py | +---idmp_v0 | | settings.py | | urls.py | | wsgi.py | | __init__.py | \---templates I created the idmp_core using python manage.py startapp idmp_core and that went well. I modified the models.py of idmp_core directory. And when I run the command python manage.py makemigrations idmp_core I get following error message (idmp) D:\Dropbox\mycode\idmp_v0>python manage.py makemigrations idmp_core Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\JMERX\Envs\idmp\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\JMERX\Envs\idmp\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\JMERX\Envs\idmp\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\JMERX\Envs\idmp\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File … -
django run code before model field access? (proxy model fields)
I'm trying to proxy the access of some models' fields. A simple example of the usage I want. @uppercase_fields(['name']) class Book(models.Model): name = models.CharField(max_length=50) # .. more fields .. Given a book instance with name='some_book': Access to book.name should return 'SOME_BOOK' I know it looks weird, but I need an access wrapper like this around model fields that will act as if I'd access the model fields normally. So a method is not an option here. I thought of using __getattr__ but I read it might mess with django internals. Any better way, preferably simple? -
Django Angular 403 Django not accepting CSRF-cookie: "CSRF token missing or incorrect."
I'm trying to create an SPA using Angular6 combined with Django. I'm having a problem with Django not accepting the csrftoken cookie I'm sending with my requests. CSRF_USE_SESSIONS = False in my settings.py Here's a picture from the browser console when the cookie gets set by a get-request: And here is the post-request using that same cookie: The cookie isn't changing between request, because if I do another get-request after that I get the same cookie-set. Here's how the cookie strategy is set up in angular: import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '@angular/http' import .... @NgModule({ declarations: [ AppComponent, RegisterComponent, LoginComponent, AlertComponent, ProfileComponent, RegisterinvoiceComponent, ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, AppRoutingModule, HttpClientModule, HttpModule ], providers: [ { provide: XSRFStrategy, useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken') } ], bootstrap: [AppComponent] }) export class AppModule { } And my Django view-code: class InvoiceViewSet(viewsets.ModelViewSet): queryset=Invoices.objects.all() serializer_class=InvoiceSerializer def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return (permissions.AllowAny(),) if self.request.method == 'POST': return (permissions.IsAuthenticated(),) return (permissions.IsAuthenticated(), IsAccountOwner(),) @method_decorator(ensure_csrf_cookie) def create(self, request): serializer=InvoiceSerializer(data=request.data) if serializer.is_valid(): user=request.user ... return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response({ 'status': 'Bad … -
Django Requiring Optional Form Field Error
I have a model and form to upload either a picture and text, or just text. My intention, actually was to make it a choice between an image, text or both and any help with that would be appreciated, but I digress. Uploading only works when an image is included, if it is just text, I get the error: The view lesyeux.views.posts didn't return an HttpResponse object. It returned None instead.The view lesyeux My model is: class Post(models.Model): image = models.ImageField(upload_to='uploaded_images', blank=True, null=True) text_post = models.CharField(max_length=1000) author = models.ForeignKey(User) My form is: class PostForm(forms.ModelForm): image = forms.FileField(label='Select an image file', help_text='Please select a photo to upload') text_post = forms.CharField(help_text="Please enter some text.") class Meta: model = Post fields = ('image', 'text_post',) exclude = ('author',) My view is: def posts(request, id=None): neighborhood = get_object_or_404(Neighborhood, id=id) form = PostForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): post = Post(image = request.FILES['image']) post = form.save(commit=False) post.author = request.user post = post.save() next = request.POST.get('next', '/') return HttpResponseRedirect(next) else: form = PostForm() posts = Post.objects.all().order_by('-id') return render(request, 'posts.html', context = {'form':form, 'posts':posts, 'neighborhood':neighborhood}) and my form is: <form id="PostForm" method="post" action="/view/{{ neighborhood.id }}/posts/" enctype="multipart/form-data"> {% csrf_token %} {% for hidden in … -
Django matching URLs for simple titles
I'm trying to match an url in a django project. My urls are like this "http://localhost:8000/article/Google-Home-Sales-Outpace-Amazons-Alexa-For-The-First-Time-13545" and in urls.py a have added: path('article/(?P<article_title>[\w\d.\'%@+-]+)', views.article) def article(request, article_title)): pass but this doesn't work. Can anyone help me? -
how to access forms field in django?
This is my forms: class signup_form(forms.ModelForm): bio = forms.TextInput() class Meta: model = User fields = ['username', 'password', 'first_name', 'last_name', 'email', 'date_joined'] And This one is my template page: urlpatterns = [ ...... url(r'^profile/(?P<username>[\w\-]+)/$', user_profile, name='user_profile'), ] And this is signup template page: {% extends parent_template|default:"tick/base_tick.html" %} {% block title %} {{ block.super }} ---> Sign Up HERE!! {% endblock %} {% block content %} <div> <div> <form action="{% url 'user_profile' username={{ from.username }} %}" method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">Create User</button> </form> </div> </div> {% endblock %} As you can see in the 'action' part of the form i want to access to the 'username' field of 'form' but i can't and the Django get me some error. What Should I do? -
Django submitting multiple forms leads to page isn't working
I'm trying to submit two crispy forms at the same time, but just can't seem to figure out how to do that. When I fill out both and then hit submit my browser just redirects me to a "Page isn't working" and nothing gets submitted. Anyone knows where the problem is? My HTML: {% block content %} /// Some tags to style the page /// <div> <form method="post" action="" class="form">{% csrf_token %} {% crispy form %} {% crispy item_form %} <input type="button" value="Add More" id="add_more"> <script> $('#add_more').click(function() { cloneMore('div.table:last', 'service'); }); </script> <div class="box-footer"> <div class="form-actions"> <input type="submit" class="btn btn-primary btn-flat pull-right" value='Create'> </div> </div> </form> </div> {% endblock %} And my views: class OfferCreateView(TemplateView): def dispatch(self, request, *args, **kwargs): return super(OfferCreateView, self).dispatch(request, *args, **kwargs) def form_valid(self, form): self.object = form.save(commit=False) self.object.last_modified_by = self.request.user self.object.save() form.save_m2m() return redirect(self.object.get_absolute_url()) model = Offer template_name = 'offers/offer_create.html' form_class = OfferCreateForm def get(self, request, *args, **kwargs): form = OfferCreateForm(self.request.GET or None) item_form = ItemCreateForm(self.request.GET or None) context = self.get_context_data(**kwargs) context['form'] = form context['item_form'] = item_form return self.render_to_response(context) -
Error uploading image using postman in django rest framework
I'm trying to create an endpoint to upload images(using postman) to a specific folder using django rest framework. This is my settings for the folder, MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This is my model, class UserMedia(models.Model): user = models.OneToOneField(User, related_name='medias', on_delete=models.CASCADE, ) profile_image_web = models.FileField(null=True) profile_image_android = models.FileField(null=True) profile_image_ios = models.FileField(null=True) thumbnail = models.FileField(null=True) This is the Serializer, class UserMediaSerializer(serializers.ModelSerializer): class Meta: model = models.UserMedia fields = ( 'profile_image_web', 'profile_image_ios', 'profile_image_android', 'thumbnail', ) This is the api, class CreateUpdateUserMedia(views.APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, **kwargs): serializer = UserMediaSerializer(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now when I try to upload ONE image corresponding to one of the fields using POSTMAN, this is the error I get. 'Cannot call `.is_valid()` as no `data=` keyword argument was ' AssertionError: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance. Which is perfectly understandable, but I dont know how to fix it. Here are my questions, How do I correctly upload images using django rest framework. I don't expect this api to be called with 4 images together, but 4 times using one image at a time, how do I … -
Django RestFramework _'NoneType' object has no attribute 'token'
I have this Serializer class for my User model: serializers.py class UserCreateSerializer(serializers.ModelSerializer): """User django serilization""" key = serializers.StringRelatedField(source='key.token', read_only=True) class Meta: model = User fields = ['phonenumber','id','email', 'username', 'key' ] def create(self, validate_data): user = User(**validate_data) user.save() return user and this views.py class UserListView(ListAPIView): '''listing all users''' permission_classes = (AllowAny,) pagination_class = SmallPagination throttle_classes = (UserRateThrottle, AnonRateThrottle,) serializer_class = UserCreateSerializer queryset = User.objects.all() filter_backends = (filters.SearchFilter,) search_fields = ('username', 'phonenumber', 'email') I include 'rest_framework.authtoken', in my settings.py and made a signal for Tokens from django Restframe work documentation. @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) urls.py urlpatterns = [ re_path(r'^users/$', views.UserListView.as_view(), name='user-list'),] so when I try to load my users List this error occurs : 'NoneType' object has no attribute 'token' for attr in attrs: try: if isinstance(instance, collections.Mapping): instance = instance[attr] else: instance = getattr(instance, attr) ... except ObjectDoesNotExist: return None if is_simple_callable(instance): try: instance = instance() except (AttributeError, KeyError) as exc: .... the error location is from : /backend/env/lib/python3.6/site-packages/rest_framework/fields.py in get_attribute -
Cannot assign "<SimpleLazyObject: <User: admin>>": "Project.manager" must be a "Profil" instance
Hello I have this error when I start saving a form. Cannot assign "<SimpleLazyObject: <User: admin>>": "Project.manager" must be a "Profil" instance. I have two applications account and project account.model.py class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo_path = time.strftime('photo/%Y/%m/%d') photo = models.ImageField(upload_to=PathAndRename(photo_path), blank=True, null=True) antity = models.CharField(max_length=50, choices=ENTITY_TYPE, default=ENTITY_TYPE[0]) biography = models.TextField(blank=True, max_length=500) location = models.CharField(max_length=30, blank=True, default='Congo-BZV') facebook_url = models.URLField(default='', blank=True) twitter_url = models.URLField(default='', blank=True) inscrit_newsletter = models.BooleanField(default=True) def __str__(self): return "Profil de {0}".format(self.user.username) project.model.py class Project( models.Model): title = models.CharField(max_length = 100) slug = models.SlugField(unique=True) image_path = time.strftime('images/%Y/%m') main_image = models.ImageField(upload_to=PathAndRename(image_path), blank=True) slogan = models.CharField(max_length=300, blank=True) category = models.ForeignKey('Category', on_delete = models.CASCADE ) description = RichTextUploadingField(blank = True, null=True) project.views.py def project_new(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): project = form.save(commit = False) project.manager = request.user project.save() else: form = ProjectForm() return render(request, 'project/project_new.html', {'form': form}) project.forms.py class ProjectForm(forms.ModelForm): title = forms.CharField(label='Titre') description = forms.CharField(widget=CKEditorUploadingWidget()) category = forms.ModelChoiceField(queryset = Category.objects.all(), label='Catégorie') #description = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 20})) class Meta: model = Project fields = ('title', 'nb_days', 'slogan', 'category', 'description') I would like every user or manager to be linked to the project they post via a form. How could I link the two models by … -
Using Tweepy in django for authentication and saving access token and access token secret of the user
I was able to use tweepy to access my own account by providing consumer key & secret and access token & secret. But i am having trouble as how to authenticate other users in my web app, and save their access token & access token secret so that to monitor that users account. I am new to this and have tried everything i could find and understand. Thanks in advance Used the given below code for accessing my own account auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) -
Having trouble associating two pieces of data
I am trying to replicate basic functionality of IMDB. Where if you look up a show it will display all the casts with their characters played. I think I have set up the models correctly. My class Cast is my hash table that is suppose to associate the other tables. I want to have the characters associated with the cast for each show. I don't really know what I'm doing. There are soo many tables and it's starting to get confusing. Models.py from django.db import models from django.urls import reverse class Genre(models.Model): name = models.CharField(max_length=200, help_text="Enter a show genre (e.g. Action, Drama, etc.)") def __str__(self): return self.name class Language(models.Model): name = models.CharField(max_length=200, help_text="Enter a show's language (e.g. English, Japanese, etc.)") def __str__(self): return self.name class People(models.Model): first_name = models.CharField(max_length=20, null=True) last_name = models.CharField(max_length=20, null=True) def __str__(self): return self.first_name class Creator(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Character(models.Model): name = models.CharField(max_length=20, null=True) def __str__(self): return self.name class Cast(models.Model): cast_show = models.ForeignKey('Show',on_delete=models.SET_NULL, null=True) cast_people = models.ManyToManyField(People, help_text='Select people who are on this show') cast_character = models.ManyToManyField(Character, help_text="sdfsdfsdf") class Show(models.Model): title = models.CharField(max_length=200) genre = models.ManyToManyField(Genre, help_text='Select a genre for this book') language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, … -
Best practices in django
Basically, I am Frontend developer, but Now I am starting full stack development with react + Django. I want to know the best practices of Django in term of how to organize code, minimum query in DB, code optimization and all things that a backend developer should know. I have read the numbers of blogs and official docs but I am unable to code with the good manner in the Django. Please suggest or share the link to blogs or doc if you have related to this. Thank you in advance. -
New to Django. Tried looking at tutorials on how to load css files and not working
The website I see when I run the server has not CSS in it, but just the HTML. So far I read that you keep CSS files in a static folder under the project directory. I have an Html template that is in the templates folder and it works perfectly when I load it from the views.home . In the HTML file, I have {% load staticfiles %} at the top of the document, and yes I have checked my installed apps for 'django.contrib.staticfiles' in the settings. Also, in the HTML document, in the href attribute I've added {% static 'style/style.css' %} which is the name of the folder under the static folder. <!DOCTYPE HTML> {% load staticfiles %} <html> <head> <title>night_sky_2</title> <meta name="description" content="website description" /> <meta name="keywords" content="website keywords, website keywords" /> <meta http-equiv="content-type" content="text/html; charset=windows-1252" /> <link rel="stylesheet" type="text/css" href="{% static 'style/style.css' %}" /> </head> -
"auth_user does not exist" when doing unit testing in django
I've been trying to solve this error for a week now and I can't seem to figure out how to fix this error. No one else who is using this repository is having the same problem as I am (I am up to date with the origin), so it has to be some sort of local issue, but I can't figure out what it would be. This happens everytime I try to run the django unit tests that we have written. There are no problems when I runserver or when I do migrations, only when testing. _______ERROR MESSAGE:_________ Liams-MBP:GrammieGram Liam2$ python manage.py test grams Creating test database for alias 'default'... Traceback (most recent call last): File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "auth_user" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 62, in handle failures … -
Unexpected failure to access global flag from inside Django test
I'm trying to add simple mocking to my tests, using a class with static fields to hold the settings (ie. singleton). This works fine when I'm running the test alone, but fails when it is ran as part of the full test suit. For reason the global class is a different class object between the test module and the tested code. ie. here is a simplified example: # in mock_settings.py class MockSettings(object): fake_random = False # in views.py def func(request) print(os.getpid(), id(MockSettings)) if MockSettings.fake_random: return HttpResponse('123') else: return HttpResponse(str(random.randint(1000))) # in tests.py def test_func(self): print(os.getpid(), id(MockSettings)) MockSettings.fake_random = True response = self.client.get('/func') self.assertEquals(response.content, '123') # fails when ran as test suite, works when runs alone Crazy thing #1: when I'm running the test alone (eg. ./manage.py test tests.TestClass.test_func), the id(MockSettings) is the same in the tests.py and the views.py, but when ran in the test suite (eg. ./manage.py test) then the pid matches but the class id is different - and thus fake_random is different... Crazy thing #2: when I tried to reproduce it on a new project, I couldn't. When I commented out all the other tests in my project it still happened. any idea why? -
How to deploy react and django in aws with a ssl and a domain
Currently, I deployed react (port 80 & 443) and django (port 8000) in aws ec2 server. I bought a domain and standard ssl cert. It sets up in react (443). In the server connection of react, it is using axios and connect to domain:8000 but I think it's not a good solution. Safari cannot connect to this kind of connection. Therefore, I add a subdomain: api.domain and change the connection from domain:8000 to api.domain. Since I don't have wildcard ssl cert, so https blocks my api.domain connection in the server. What is the best practice of this case?